如何在Spring XML元数据配置中为bean设置ServletContext属性 [英] How to set ServletContext property for a bean in Spring XML metadata configuration
问题描述
我尝试在此处搜索SO,但找不到解决方案.我有一些类似下面的XML元数据.
I tried searching here on SO but i couldn't find a solution. I have some XML metadata like the following.
<bean class="javax.servlet.ServletContext" id="servletContext" />
<bean class="com.abc.ProductController">
<property name="servletContext" ref="servletContext"/>
</bean>
使用这种配置,我得到一个例外,说"javax.servlet.ServletContext"
是一个接口,它无法创建ID为servletContext
的bean. ProductController类位于无法修改的某个jar中,但我希望将其作为应用程序中的bean.它具有自动关联的ServletContext属性.
With this configuration I am getting an exception saying that "javax.servlet.ServletContext"
is an interface and it couldn't create a bean with the id servletContext
. The ProductController class is in some jar which I can't modify but I want it as a bean in my application. It has ServletContext property autowired.
推荐答案
如果需要在XML配置spring应用程序中为ServletContext
创建bean,则可以使用BeanFactory<ServletContext>
实现ServletContextAware
If you need to create a bean for ServletContext
in a XML config spring application, you could use a BeanFactory<ServletContext>
implementing ServletContextAware
public class ServletContextFactory implements FactoryBean<ServletContext>,
ServletContextAware{
private ServletContext servletContext;
@Override
public ServletContext getObject() throws Exception {
return servletContext;
}
@Override
public Class<?> getObjectType() {
return ServletContext.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
}
然后您可以声明:
<bean class="org.app.ServletContextFactory" id="servletContext" />
<bean class="com.abc.ProductController">
<property name="servletContext" ref="servletContext"/>
</bean>
这篇关于如何在Spring XML元数据配置中为bean设置ServletContext属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!