Spring injection Into Servlet

后端 未结 4 1812
Happy的楠姐
Happy的楠姐 2020-11-29 21:17

So I have seen this question:

Spring dependency injection to other instance

and was wondering if my method will work out.

1) Declare beans in my Spri

4条回答
  •  孤独总比滥情好
    2020-11-29 21:47

    What you are trying to do will make every Servlet have its own ApplicationContext instance. Maybe this is what you want, but I doubt it. An ApplicationContext should be unique to an application.

    The appropriate way to do this is to setup your ApplicationContext in a ServletContextListener.

    public class SpringApplicationContextListener implements ServletContextListener {
            @Override
        public void contextInitialized(ServletContextEvent sce) {
            ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    
            sce.getServletContext().setAttribute("applicationContext", ac);            
        }
        ... // contextDestroyed
    }
    

    Now all your servlets have access to the same ApplicationContext through the ServletContext attributes.

    @Override
    public void init(ServletConfig config) throws ServletException {
       super.init(config);
    
       ApplicationContext ac = (ApplicationContext) config.getServletContext().getAttribute("applicationContext");
    
       this.apiData = (ApiData)ac.getBean("apiData");
       this.apiLogger = (ApiLogger)ac.getBean("apiLogger");
    }
    

提交回复
热议问题