ApplicationEventPublisher

ApplicationEventPublisher

我有一个下一个customEventPublisher-class:

@Component
public class CustomEventPublisher {

@Autowired
private static ApplicationEventPublisher applicationEventPublisher;

public static void doStuffAndPublishAnEvent(User user) {
    OnPostUserDataEvent onPostUserDataEvent = new OnPostUserDataEvent(user, REST_URL);
    applicationEventPublisher.publishEvent(onPostUserDataEvent);
   }
 }


在Service中调用的publishEvent方法:

 public User create(User user) {

    CustomEventPublisher.doStuffAndPublishAnEvent(user);

    return repository.save(user);
}


配置:

 <context:component-scan base-package="example.service"/>
 <context:component-scan base-package="example.util.emailUtil"/>


事件通过以下方式实现:

public class OnPostUserDataEvent extends ApplicationEvent {

private static final long serialVersionUID = 1L;
private String appUrl;

private User user;

public OnPostUserDataEvent(User user, String appUrl) {
    super(user);
    this.user = user;
    this.appUrl = appUrl;
    }
}


我为以下原因捕获了NullPointedException:

 applicationEventPublisher.publishEvent(onPostUserDataEvent)


也许ApplicationEventPublisher不是@Autowired,但我不明白为什么。

最佳答案

问题是您正在与AOP作战。 doStuffAndPublishAnEvent方法是静态的,因此不会在可以注入ApplicationEventPublisher的实例上调用它。

为了克服这个问题,您必须使doStuffAndPublishAnEvent为非静态并将CustomEventPublisher注入到您的服务中,以便您可以在实例上的代理上调用该方法。

08-18 05:58