How to set ServletContext property for a bean in Spring XML metadata configuration

后端 未结 4 2067
名媛妹妹
名媛妹妹 2021-01-14 23:14

I tried searching here on SO but i couldn\'t find a solution. I have some XML metadata like the following.



        
相关标签:
4条回答
  • 2021-01-14 23:36

    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.

    0 讨论(0)
  • 2021-01-14 23:38

    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();
        }
    }
    
    0 讨论(0)
  • 2021-01-14 23:57

    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>
    
    0 讨论(0)
  • 2021-01-14 23:59

    Just autowire the context in your controller:

    @Autowired
    private ServletContext context;
    
    0 讨论(0)
提交回复
热议问题