我有一个类初始化应用程序
@Component
public class InitApp implements ServletContextListener {
@Autowired
ConfigrationService weatherConfService;
/** Creates a new instance of InitApp */
public InitApp() {
}
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println(weatherConfService);
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
和 web.xml 中的监听器:
<listener>
<listener-class>com.web.Utils.InitApp</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
confService 打印 --> null
有什么问题吗?
当我遇到同样的问题时,我想到了一些想法。
第一个是使用 Spring utils 从侦听器内的 Spring 上下文中检索 bean:
Ex:
@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
}
}
如果你只有一两颗豆子,这很有效。否则会变得乏味。另一种选择是显式调用 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
,确保春季ContextLoaderListener
定义于web.xml
强制首先加载(Web 描述符中定义的侦听器先于注释定义的侦听器加载)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)