Spring dependency injection to other instance

后端 未结 1 653
甜味超标
甜味超标 2021-01-27 02:50

from the app-context.xml:

 
    

        
相关标签:
1条回答
  • 2021-01-27 03:36

    Spring is atowiring your bean correctly, the problem is that servlet container instantiates your servlet independently of spring. So you basically have two different instances - one created by spring and another created by container.

    One workaround is to use ServletContextAttributeExporter, by putting the following in your app-context.xml:

    <bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
     <property name="attributes">
         <map>
             <entry key="userDao">
                 <ref bean="userDao"/>
             </entry>
          </map>
    </property>
    

    and then, in your servlet:

    protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    
        UserDao userDao = (UserDao)getServletContext().getAttribute("userDao");
    
        // do something with userDao
    
        PrintWriter writer = response.getWriter();
    
        writer.write("hello");
    }
    

    another is to access the WebApplicationContext directly:

    protected void doGet(HttpServletRequest reqest, HttpServletResponse response)
                                         throws ServletException, IOException {
    
        WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        UserDao userDao =(UserDao)springContext.getBean("userDao");
    
     }
    

    ... or simply use Spring MVC and let it autowire everything like it should.

    Also see this blog post. It might be easier to convert your servlet to HttpRequestHandler and let it be served by HttpRequestHandlerServlet, both provided by spring.

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