spring getbean 用单例模式

来源:互联网 发布:js实现div旋转 编辑:程序博客网 时间:2024/04/28 15:11

项目中用到Struts 1.2.9 + Spring 2.5 + hibernate 3.2.5框架

OperateLogService 是一个操作日志的service,里面有个插日志的方法logger,因为这个方法被很多地方调用,
所以我搞了这个OperateLogAddServiceImpl ,加了个静态方法, 然后使用getbean,这样的话调用的地方就不需要注入OperateLogService 这个service

package com.lenovo.platform.operatelog.service.impl;
import com.lenovo.platform.exception.AppTranException;
import com.lenovo.platform.operatelog.service.OperateLogService;
import com.lenovo.platform.security.entity.OperateLog;
import com.lenovo.reconciliation.service.impl.SpringContextUtil;

public class OperateLogAddServiceImpl {
public static void saveOperateLog(OperateLog operateLog) throws AppTranException{
OperateLogService operateLogService = (OperateLogService)SpringContextUtil.getBean("operateLogService");
operateLogService.logger(operateLog);
}
}

 

结果系统偶发性的出现问题,抛出下列错误信息,一重启tomcat,问题就没有了,但是过段时间又会重现,并且问题只在生产平台发生,本机无问题,从错误信息来看,说是什么事务方面的问题,当时以为是数据源或者事务什么的问题

Pre-bound JDBC Connection found! HibernateTransactionManager does not support running within DataSourceTransactionManager if told to manage the DataSource itself. It is recommended to use a single HibernateTransactionManager for all transactions on a single DataSource, no matter whether Hibernate or JDBC access

 

但是实际上是getbean的问题,将获取service实例改成下面单例模式,问题随即解决,问题虽然解决,但是还是不太明白原因,尤其是抛出来的错误跟问题有点不搭边

 

package com.lenovo.platform.operatelog.service.impl;
import com.lenovo.platform.exception.AppTranException;
import com.lenovo.platform.operatelog.service.OperateLogService;
import com.lenovo.platform.security.entity.OperateLog;
import com.lenovo.reconciliation.service.impl.SpringContextUtil;
public class OperateLogAddServiceImpl {
 private  static OperateLogService operateLogService = null;
 synchronized private static OperateLogService getOperateLogService(){
  if(operateLogService == null){
   operateLogService = (OperateLogService)SpringContextUtil.getBean("operateLogService");
  }
  return operateLogService;
 }
 public static void saveOperateLog(OperateLog operateLog) throws AppTranException{
  OperateLogService operateLogService = getOperateLogService();
  operateLogService.logger(operateLog);
 }
}

原创粉丝点击