论坛首页 入门讨论版 Spring

怎样在项目启动时得到Spring管理的对象

浏览 267 次
该帖已经被评为新手帖
作者 正文
最后更新时间:2008-04-01
有个项目是用ssh框架的,所有的dao,service都交给spring管理,项目使用的也是openSessioninView这种方式来管理
hibernate的session.现在我想在项目一启动的时候加载数据库的东西,我是准备在一个servlet里面来调dao,service这些东西来操作数据库,可是好像这样不行,得spring管理的bean的时候总是报null,估计是spring还没有加载,这样的问题,应该怎么解决啊?我是把这个Servlet的加载设为1。项目一启动就加载这个Servlet了。
   
最后更新时间:2008-04-01
项目启动时要做一些操作的话,不要用servlet.servlet是处理请求用的.写一个listener吧.在web.xml里,spring的ContextLoaderListener后边,写上你的listener.

<listener>
		<listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>

	<listener>
		<listener-class>
			com.my.web.SysListener
		</listener-class>
	</listener>


然后可以在listener中:

public class SysListener implements ServletContextListener{
    public void contextInitialized(ServletContextEvent se){
        WebApplicationContext wa =   WebApplicationContextUtils.getWebApplicationContextse.getServletContext());
        IXXXService xxxService = (IXXXService )wa.getBean("xxxService ");
        //Do something here...
    }
}
   
0 请登录后投票
最后更新时间:2008-04-01
谢谢yyjn12,我会先按你说的方法试一下。
Servlet是可以在项目启动时加载的
把启动级别改成正数
<load-on-startup>1</load-on-startup>
然后重写
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
}
在init()方法里面就可以写你准备让项目启动时执行的方法了。看样子是servlet在spring加载前执行了,所以得不到spring的注入 。
   
0 请登录后投票
论坛首页 入门讨论版 Spring

跳转论坛:
JavaEye推荐