我不确定它是否有效,我们有一个加载文件.txt
的项目,即在以前的部署中创建的用户。问题是Applicationcontext
未加载,并抛出NullPointerException
,因为加载文件的方法是@Autowired,这就是我尝试解决的问题:
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class TestListener implements ApplicationListener{
@Override
public void onApplicationEvent(ApplicationEvent event) {
}
}
这是项目和监听器的web.xml:
<listener>
<listener-class>TestListener</listener-class>
</listener>
重点是创建一个监听器,这是正确的吗?
答案 0 :(得分:0)
有两种选择:
的InitializingBean:
@Component
public class FileLoader implements InitializingBean {
public void afterPropertiesSet() throws Exception {
// load file
}
}
这应该在上下文加载后调用。
@PostConstruct:
@Component
public UserService {
private List<Customer> registeredCustomers;
// ...
@PostConstruct
public void loadPreviouslyRegisteredUsers() {
registeredCustomers = loadFile();
}
}
我更喜欢这个;在创建服务bean之后将调用@PostConstruct方法,这是加载文件的最佳时机。
很抱歉,如果这不能真正回答您关于ApplicationContextListener
的问题,但听起来就像您正在尝试做的那样。