user1116377
user1116377

Reputation: 699

Spring dependency injection to other instance

from the app-context.xml:

 <bean id="userDao" class="com.vaannila.dao.UserDAOImpl">
    <property name="sessionFactory" ref="mySessionFactory"/>
</bean>  

<bean name="MyServiceT" class="com.s.server.ServiceT">
    <property name="userDao" ref="userDao"/>
</bean> 

and inside ServiceT.java:

private UserDAO userDao;

public void setUserDao(UserDAO userDao){
    this.userDao = userDao;
}

the issue is: the setUserDao is called when the server goes on but when I call my doGet method:

    protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    PrintWriter writer = response.getWriter();

    writer.write("hello");
    }

the userDao is null. I put a breakpoint inside the setUserDao method and than another one inside the doGet method and saw that it is not the same insatnce... what is the reason? how can I fix it? thanks!

Upvotes: 1

Views: 2605

Answers (1)

soulcheck
soulcheck

Reputation: 36777

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.

Upvotes: 3

Related Questions