springmvc 事務注冊有很多種方法,在此我只mark 用注解方式添加transaction不生效的解決辦法。 springmvc 注解方法添加事務步驟: 1.在 spring的 root-context.xml (WEB-INF/)文件中添加事物管理: <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="mysqlDataSource"> </bean> 或者 <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" > <property name="dataSource" ref="mysqlDataSource"/> </bean> 2.添加注解驅動 <tx:annotation-driven transaction-manager="txManager"/> 3.在需要添加事物管理的java類上添加@Transactional @Service public class HomeServiceImpl implements HomeService { @Autowired private HomeDao homeDao; public static final Logger LOGGER = LoggerFactory.getLogger(HomeServiceImpl.class); /** * note:need add throw RuntimeException */ @Transactional @Override public int updateAgeNonException() throws Exception { try { Map<String,Integer> map = new HashMap<String,Integer>(); map.put("age", 10); homeDao.updateAge(map); map.put("age", 30); homeDao.updateAge(map); } catch (Exception e) { LOGGER.error("debug ****", e); throw new RuntimeException(); } return 0; } @Override public int updateAgeException() throws Exception { try { Map<String,Integer> map = new HashMap<String,Integer>(); 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 new RuntimeException(); } return 0; } public List<String> queryData() { return homeDao.queryData(); } } 事物添加以上3步就ok了。 啟動server運行一下,看事物是否生效。一般情況下是不會生效的。 原因在于,service方法被注入了2次。解決辦法: 1.在root-context.xml 中添加包掃描,掃描所有需要注入的包 <context:component-scan base-package="com.ck.fm.*"></context:component-scan>
2.在servlet-context.xml配置文件中,包掃描的時候排除掃描service <context:component-scan base-package="com.ck.fm.*" > <!-- prevented Service injected twice --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan> |
|