简体   繁体   中英

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.

<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 . 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.

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;
    }

}

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.

The solution is to have com.abc.ProductController implement ServletContextAware and then Spring will set it for you.

With java config use ServletContextFactory created by Serge Ballesta above and:

@Configuration
public class WebAppConfiguration {

    @Autowired
    private ServletContextFactory servletContextFactory;

    @Bean
    public ServletContextFactory servletContextFactory() {
         return new ServletContextFactory();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM