标签:
springmvc 事务注册有很多种方法,在此我只mark 用注解方式添加transaction不生效的解决办法。
springmvc 注解方法添加事务步骤:
1.在 spring的 root-context.xml (WEB-INF/)文件中添加事物管理:
或者
2.添加注解驱动
3.在需要添加事物管理的java类上添加@Transactional
@Servicepublic class HomeServiceImpl implementsHomeService {
@AutowiredprivateHomeDao homeDao;public static final Logger LOGGER = LoggerFactory.getLogger(HomeServiceImpl.class);/*** note:need add throw RuntimeException*/@Transactional
@Overridepublic int updateAgeNonException() throwsException {try{
Map map = new HashMap();
map.put("age", 10);
homeDao.updateAge(map);
map.put("age", 30);
homeDao.updateAge(map);
}catch(Exception e) {
LOGGER.error("debug ****", e);throw newRuntimeException();
}return 0;
}
@Overridepublic int updateAgeException() throwsException {try{
Map map = new HashMap();
map.put("age", 10);
homeDao.updateAge(map);//exception
System.out.println(2/0);
map.put("age", 30);
homeDao.updateAge(map);
}catch(Exception e) {
LOGGER.error("debug ****", e);throw newRuntimeException();
}return 0;
}public ListqueryData() {returnhomeDao.queryData();
}
}
事物添加以上3步就ok了。
启动server运行一下,看事物是否生效。一般情况下是不会生效的。
原因在于,service方法被注入了2次。解决办法:
1.在root-context.xml 中添加包扫描,扫描所有需要注入的包
2.在servlet-context.xml配置文件中,包扫描的时候排除扫描service
标签: