I want to inject an object in servlet using Spring

后端 未结 2 1190
Happy的楠姐
Happy的楠姐 2020-12-19 10:32

I have a two servlets in my application and I want an object of class A to be injected to both the servlets, and I would also like the same ApplicationContext throughout the

2条回答
  •  别那么骄傲
    2020-12-19 10:50

    You're mixing up two concepts: Servlets and Spring's ApplicationContext. Servlets are managed by your Servlet container, let's take Tomcat for example. The ApplicationContext is managed by Spring.

    When you declare a Servlet in your deployment descriptor as

    
        servletOne
        mypackage.servletOne
    
    
        servletOne
        /servletOne
    
    

    The Servlet container will create an instance of your mypackage.servletOne class, register it, and use it to handle requests. This is what it does with the DispatcherServlet which is the basis of Spring MVC.

    Spring is an IoC container that uses ApplicationContext to manage a number of beans. The ContextLoaderListener loads the root ApplicationContext (from whatever location you tell it to). The DispatcherServlet uses that root context and must also load its own. The context must have the appropriate configuration for the DispatcherServlet to work.

    Declaring a bean in the Spring context, like

    
            
    
    

    regardless of the fact that it is of the same type as the declared in web.xml, is completely unrelated. The bean above has nothing to do with the declaration in the web.xml.

    As in my answer here, because the ContextLoaderListener puts the ApplicationContext it creates into the ServletContext as an attribute, that ApplicationContext is available to any Servlet container managed object. As such, you can override the HttpServlet#init(ServletConfig) in your custom HttpServlet classes, like so

    @Override
    public void init(ServletConfig config) throws ServletException {
       super.init(config);
    
       ApplicationContext ac = (ApplicationContext) config.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    
       this.someObject = (SomeBean)ac.getBean("someBeanRef");
    }
    

    assuming that your root ApplicationContext contains a bean called someBeanRef.

    There are other alternatives to this. This, for example.

提交回复
热议问题