[英]How to set ServletContext property for a bean in Spring XML metadata configuration
I tried searching here on SO but i couldn't find a solution. 我尝试在这里搜索,但我找不到解决方案。 I have some XML metadata like the following. 我有一些XML元数据,如下所示。
<bean class="javax.servlet.ServletContext" id="servletContext" />
<bean class="com.abc.ProductController">
<property name="servletContext" ref="servletContext"/>
</bean>
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
. 使用此配置,我得到一个例外,说"javax.servlet.ServletContext"
是一个接口,它无法使用id servletContext
创建一个bean。 The ProductController class is in some jar which I can't modify but I want it as a bean in my application. ProductController类在某个jar中,我无法修改,但我希望它在我的应用程序中作为bean。 It has ServletContext property autowired. 它具有自动装配的ServletContext属性。
If you need to create a bean for ServletContext
in a XML config spring application, you could use a BeanFactory<ServletContext>
implementing ServletContextAware
如果需要在XML config spring应用程序中为ServletContext
创建bean,可以使用实现ServletContextAware
的BeanFactory<ServletContext>
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;
}
}
You can then declare : 然后你可以声明:
<bean class="org.app.ServletContextFactory" id="servletContext" />
<bean class="com.abc.ProductController">
<property name="servletContext" ref="servletContext"/>
</bean>
Just autowire the context in your controller: 只需在控制器中自动连接上下文:
@Autowired
private ServletContext context;
You cannot reference the servlet context in your XML like this because its lifecycle is controlled by the servlet container. 您不能像这样在XML中引用servlet上下文,因为它的生命周期由servlet容器控制。
The solution is to have com.abc.ProductController
implement ServletContextAware and then Spring will set it for you. 解决方案是让com.abc.ProductController
实现ServletContextAware然后Spring会为你设置它。
With java config use ServletContextFactory created by Serge Ballesta above and: 使用java配置使用上面由Serge Ballesta创建的ServletContextFactory和:
@Configuration
public class WebAppConfiguration {
@Autowired
private ServletContextFactory servletContextFactory;
@Bean
public ServletContextFactory servletContextFactory() {
return new ServletContextFactory();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.