Spring依赖注入到其他实例
从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>
和ServiceT.java内部:
private UserDAO userDao;
public void setUserDao(UserDAO userDao){
this.userDao = userDao;
}
问题是:当服务器继续运行时调用setUserDao,但当我调用我的doGet方法时:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
writer.write("hello");
}
userDao为空。 我在 setUserDao 方法中放置了一个断点,然后在 doGet 方法中放置了另一个断点,发现它不一样......原因是什么?我该如何修复它? 谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Spring正在正确连接你的bean,问题是servlet容器独立于spring实例化你的servlet。所以你基本上有两个不同的实例 - 一个由 spring 创建,另一个由容器创建。
一种解决方法是使用
ServletContextAttributeExporter
,将以下内容放入 app-context.xml:,然后放入 servlet:
另一种方法是直接访问
WebApplicationContext
:.. . 或者简单地使用 Spring MVC 并让它自动装配所有内容。
另请参阅此博文。将 servlet 转换为 HttpRequestHandler 并让其由 HttpRequestHandlerServlet 提供服务可能会更容易,两者均由 spring 提供。
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:and then, in your servlet:
another is to access the
WebApplicationContext
directly:... 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 byHttpRequestHandlerServlet
, both provided by spring.