我正在尝试在应用程序启动期间初始化一些bean,这些bean将从静态共享内存结构中读取。我之前使用的是@PostContruct,但我希望转向基于事件的更多初始化,以便我可以使用Spring AOP功能(配置,资源等)并避免重复自己。
所有数据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
}
}
我还可以尝试在启动SpringApplication后返回的main()
函数的末尾初始化这些类。
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
// Can I initialize the DataInterfaces here???
}
}
似乎应该有更好的方法。
修改
我最终使用了以下解决方案,因为我无法收到Spring docs中列出的任何Context*
个事件。
@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();
}
}
}