springmvc 用注解方式添加事务不生效解决方法

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>
原文地址:https://www.cnblogs.com/rengised/p/5748901.html