gpt4 book ai didi

java - ApplicationEventPublisher NullPointerException

转载 作者:行者123 更新时间:2023-12-02 08:57:35 24 4
gpt4 key购买 nike

我有一个下一个 customEventPublisher 类:

@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);
}
}

服务中调用的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 方法是静态的,因此不会在可以注入(inject) ApplicationEventPublisher 的实例上调用它。

要克服这个问题,您必须将 doStuffAndPublishAnEvent 设置为非静态,并将 CustomEventPublisher 注入(inject)到您的服务中,以便您可以通过实例调用代理上的方法。

关于java - ApplicationEventPublisher NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60399499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com