问题描述
我想在 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
实现这一目标的正确方法是什么?
What is the correct way to achieve this?
推荐答案
我通过删除侦听器 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!