I want to inject an object in servlet using Spring

后端 未结 2 1191
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:38

    If you want to use @Autowired or set property via applicationContext.xml then annotate your class with @Controller annotation

    0 讨论(0)
  • 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

    <servlet>
        <servlet-name>servletOne</servlet-name>
        <servlet-class>mypackage.servletOne</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>servletOne</servlet-name>
        <url-pattern>/servletOne</url-pattern>
    </servlet-mapping>
    

    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

    <bean id="servletFirst" class="mypackage.servletOne">
            <property name="message" ref="classObject" />
    </bean>
    

    regardless of the fact that it is of the same type as the <servlet> declared in web.xml, is completely unrelated. The bean above has nothing to do with the <servlet> 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.

    0 讨论(0)
提交回复
热议问题