[英]Spring application initalization
我試圖在應用程序啟動期間初始化一些Bean,這些Bean將從靜態共享內存結構中讀取。 我以前使用過@PostContruct,但想轉向基於事件的初始化,這樣我就可以利用Spring AOP的功能(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
}
}
我也可以嘗試在啟動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();
}
}
}
使用Spring應用程序事件偵聽器,請參閱Spring Framework中更好的應用程序事件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.