私は同じ問題を抱えていたので、いくつかのアイデアが思い浮かびました。
最初の 1 つは、Spring ユーティリティを使用して、リスナー内の Spring コンテキストから Bean を取得することです。
元:
@WebListener
public class CacheInitializationListener implements ServletContextListener {
/**
* Initialize the Cache Manager once the application has started
*/
@Override
public void contextInitialized(ServletContextEvent sce) {
CacheManager cacheManager = WebApplicationContextUtils.getRequiredWebApplicationContext(
sce.getServletContext()).getBean(CacheManager.class);
try {
cacheManager.init();
} catch (Exception e) {
// rethrow as a runtime exception
throw new IllegalStateException(e);
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
}
これは、Bean が 1 つまたは 2 つしかない場合にうまく機能します。そうしないと、退屈になる可能性があります。もう 1 つのオプションは、Spring の Autowire ユーティリティを明示的に呼び出すことです。
@WebListener
public class CacheInitializationListener implements ServletContextListener {
@Autowired
private CacheManager cacheManager;
/**
* Initialize the Cache once the application has started
*/
@Override
public void contextInitialized(ServletContextEvent sce) {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
try {
cacheManager.init();
} catch (Exception e) {
// rethrow as a runtime exception
throw new IllegalStateException(e);
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
}
これらの両方のソリューションの警告は、これらのいずれかが機能する前に、Spring コンテキストを最初にロードする必要があることです。を使用してリスナーの順序を定義する方法がないことを考えると@WebListener
、Springが強制的に最初にロードされるように でContextLoaderListener
定義されていることを確認してください (Web 記述子で定義されたリスナーは、アノテーションで定義されたリスナーの前にロードされます)。web.xml