首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java Web开发 >

web起动的时候使用Spring容器中的bean

2012-12-27 
web启动的时候使用Spring容器中的beanjava web项目中,我继承SerlvtContextListener写了一个listener,当web

web启动的时候使用Spring容器中的bean
java web项目中,我继承SerlvtContextListener写了一个listener,当web容器启动的时候就从数据库在加载数据进行一系列的初始化,但是我的listener种引用了dao组件,而dao组件是交给Spring容器管理的,这样做,但是启动的时候,报了“空指针”错误,我想可能是dao组件没有初始化的问题,但是我确实又要这么做,哪位大侠给我一个好方法,如果是继承Spring自己的一个listener,同样也是出现这样的问题
[最优解释]
可以把加载Spring文件的方法写在一个类里面.
然后在你的那个listener里面调用该类的方法去加载spring配置文件,
并找到该bean,实现注入.


public class AppUtil{
   private static AppUtil instance;
   private static ApplicationContext context;
   public static ApplicationContext getInstance(){
     if(null == instance){
         instance = new AppUtil();
     }
     String [] names = {classpath:applicationContext.xml};
     context = new ClassPathXmlApplicationContext(names);
   }

   public static void main(String [] args){
     UserDao userDao = (UserDao)AppUtil.context.getBean("userDao");
     userDao.getUserById();
   }
}

[其他解释]
引用:
可以把加载Spring文件的方法写在一个类里面.
然后在你的那个listener里面调用该类的方法去加载spring配置文件,
并找到该bean,实现注入.
[code=Java]
public   class   AppUtil{
        private   static   AppUtil   instance;
        private   static   Ap……

就是这样 直接读取配置文件获取 对象就行了
[其他解释]
把org.springframework.web.context.ContextLoaderListener
放到你的Listener前面,
然后从你的Listener中用“标准”的方式来获取bean可能会更好一些

   ApplicationContext ctx = 
      WebApplicationContextUtils.
         getWebApplicationContext(session.getServletContext());
 
   ctx.getBean("dao");


[其他解释]
操作不当的话会有两次加载的
[其他解释]
引用:


你有没有配置自动事物管理,最好把对应的配置贴出来看看.

[其他解释]
引用:
可以把加载Spring文件的方法写在一个类里面.
然后在你的那个listener里面调用该类的方法去加载spring配置文件,
并找到该bean,实现注入.
[code=Java]
public   class   AppUtil{
        private   static   AppUtil   instance;
        private   static   Ap……


我有点不明白的是,如果是Spring启动以后,我在类中引用一个dao,有getter、setter方法,Spring也是自动帮我们注入的啊,这个Spring也启动了,怎么不能自动帮我注入啊?
[其他解释]
引用:
操作不当的话会有两次加载的

这个怎么说,可以说清楚点吗?
------其他解决方案--------------------


引用:
引用:


你有没有配置自动事物管理,最好把对应的配置贴出来看看.

自动事务管理,我是配置在service层的一些包里面的,恩 我试试配置一下看看
[其他解释]
System.out.println("hello world!");

[其他解释]
out.println("hello world too");

热点排行