本文介绍了Spring - 将依赖项注入到ServletContextListener中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将一个依赖项注入到一个 ServletContextListener
中。但是,我的做法不行。我可以看到Spring正在调用setter方法,但是后来当调用 contextInitialized
时,该属性为 null
。
I would like to inject a dependency into a ServletContextListener
. However, my approach is not working. I can see that Spring is calling my setter method, but later on when contextInitialized
is called, the property is 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
正确的方法是什么?
推荐答案
我通过删除监听器bean并为我的属性创建一个新bean。然后我在我的监听器中使用以下内容来获取属性bean:
I resolved this by removing the listener bean and creating a new bean for my properties. I then used the following in my listener, to get the properties bean:
@Override
public void contextInitialized(ServletContextEvent event) {
final WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
final Properties props = (Properties)springContext.getBean("myProps");
}
这篇关于Spring - 将依赖项注入到ServletContextListener中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!