[英]Spring - Injecting a dependency into a ServletContextListener
我想将一个依赖项注入ServletContextListener
。 但是,我的方法不起作用。 我可以看到Spring正在调用我的setter方法,但是稍后在调用contextInitialized
时,该属性为null
。
这是我的设置:
ServletContextListener:
public class MyListener implements ServletContextListener{
private String prop;
/* (non-Javadoc)
* @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
*/
@Override
public void contextInitialized(ServletContextEvent event) {
System.out.println("Initialising listener...");
System.out.println(prop);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
}
public void setProp(String val) {
System.out.println("set prop to " + prop);
prop = val;
}
}
web.xml :(这是文件中的最后一个监听器)
<listener>
<listener-class>MyListener</listener-class>
</listener>
applicationContext.xml中:
<bean id="listener" class="MyListener">
<property name="prop" value="HELLO" />
</bean>
输出:
set prop to HELLO
Initialising listener...
null
实现这一目标的正确方法是什么?
dogbane的答案(已接受)有效,但由于bean的实例化方式,它使测试变得困难。 我更喜欢这个问题中提出的方法:
@Autowired private Properties props;
@Override
public void contextInitialized(ServletContextEvent sce) {
WebApplicationContextUtils
.getRequiredWebApplicationContext(sce.getServletContext())
.getAutowireCapableBeanFactory()
.autowireBean(this);
//Do something with props
...
}
我通过删除监听器bean并为我的属性创建一个新bean来解决这个问题。 然后我在我的监听器中使用以下内容来获取属性bean:
@Override
public void contextInitialized(ServletContextEvent event) {
final WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
final Properties props = (Properties)springContext.getBean("myProps");
}
如前所述,ServletContextListener是由服务器创建的,因此它不受spring管理。
如果您希望收到ServletContext的通知,可以实现该接口:
org.springframework.web.context.ServletContextAware
你不能有弹簧这样做,正如已经说明的那样是由服务器创建的。 如果需要将params传递给侦听器,可以在web xml中将其定义为context-param
<context-param>
<param-name>parameterName</param-name>
<param-value>parameterValue</param-value>
</context-param>
在Listener中,您可以像下面一样检索它;
event.getServletContext().getInitParameter("parameterName")
编辑1:
请参阅以下链接以获取其他可能的解决方
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.