加载Applicationcontext后添加监听器spring web

Add listener spring web after Applicationcontext is loaded

我不确定它是否有效,我们有一个加载文件 .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>

重点是创建监听器,这样对吗?

想到两个选项:

初始化Bean:

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

我更喜欢这个; @PostConstruct方法会在服务bean创建完成后被调用,这是加载文件的最佳时机。

抱歉,如果这不能真正回答您关于 ApplicationContextListener 的问题,但听起来这就是您想要做的。