我正在尝试在应用程序启动期间初始化一些bean,这些bean将从静态共享内存结构中读取。我以前使用过@PostContruct,但想转移到一个更基于事件的初始化,这样我就可以使用Spring特性(Config、Resources等)。避免重复自己。
所有数据bean都实现了这个接口:
public interface DataInterface {
public void loadData();
public List<String> getResults(String input);
}我尝试过实现ServletContextListener和WebApplicationInitializer接口,但似乎都没有被调用。
@Service
public class AppInit implements WebApplicationInitializer {
@Autowired
DataInterface[] dataInterfaces;
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// This does not get called
for (DataInterface interface : dataInterfaces)
interface.loadData();
}
}
@WebListener
public class AppContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
// does not get called
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
// does not get called
}
}我还可以尝试在main()函数的末尾初始化这些类,该函数在启动SpringApplication后返回。
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
// Can I initialize the DataInterfaces here???
}
}看来应该有更好的办法。
编辑:
最后我使用了以下解决方案,因为我无法接收春季医生中列出的任何春季医生事件。
@Component
public class DalInitializer implements ApplicationListener {
@Autowired
DataInterface[] dataInterfaces;
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
if (applicationEvent.getClass() == ApplicationReadyEvent.class) {
for (DataInterface interface : dataInterfaces)
interface.loadData();
}
}
}发布于 2017-01-30 23:05:18
使用spring应用程序事件侦听器,请参阅Spring框架中更好的应用程序事件
https://stackoverflow.com/questions/41946852
复制相似问题