Spring 解决线程中无法获得数据库连接

来源:互联网 发布:1024最新 知乎 编辑:程序博客网 时间:2024/05/01 15:57

吴宗坡 博客 Spring解决线程中无法获得数据库连接

项目使用Hibernate,Hibernate交给了Spring管理。

Class:CgzServiceImpl

@Component("cgzService")
public class CgzServiceImpl implements CgzService {

    @Resource
    private StatsCommonService statServ;
    @Resource
    private CommonService updateServ;
    
    @Override

    public void updateBaseDate(String time) {

    ...

   }

}

需要:需要创建一个线程,隔一段时间执行一次UpdateBaseDate(String time)方法。 由于在线程中无法通过注解得到CgzServiceImpl对象,也不能通过new的方式创建CgzServiceImpl对象,否则对象为空。这是为什么哪?

因为:这个类CgzServiceImpl通过@Component("cgzService")交给spring容器管理了,那么上面的两种方式都无法从spring容器中获得数据库连接。为什么无法获得连接,因为线程类没有交给spring管理,同new一个CgzServiceImpl对象,也无法从spring容器中获得数据库连接。

所以当你使用CgzService cgz=new CgzServiceImpl(); 时或者

CgzServiceImpls cgz;时

cgz.updateBaseDate("2012-01-01"); 会报空指针异常。


解决方法:

创建一个Spring容器 ApplicationContext  ctx= new ClassPathXmlApplicationContext("beans.xml"); //整个项目只创建一个就可以,多了容易内存溢出!!!

CgzService cgzS=(CgzService )ctx.getBean("cgzService");

cgzS.updateBaseDate("2012-01-01"); 就不回报空异常的错误了。