一、首先配置好基础的数据源及注解管理器
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="cn.hexing.quartz.util;cn.hexing.fk.bp.newDbHelper">
</context:component-scan>
<bean id="bp.Test_batch" class="cn.hexing.quartz.util.Test_batch"></bean>
最下面的注解扫描包好像可以不要;不要也可以扫描到有注解的类
二、带注解的类
package cn.hexing.quartz.util;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
public class Test_batch {
public void test_relay(POJO pojo) {
test_batch(pojo);
}
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void test_batch(POJO pojo)) {
//入库操作
}
}
三、测试方法类
void mian(){
POJO pojo, pojo1, pojo2;
Test_batch test_batch = (Test_batch) AfwUtil.getBean("bp.Test_batch");
test_batch.test_batch(pojo1); /此种调用方式可以作为一个事务提交
A1
test_batch.test_relay(pojo2);
//此种调用方式不可以作为一个事务提交
A2
Test_batch test_batch1 = new Test_batch();
test_batch1.test_batch(pojo1); /此种调用方式不可以作为一个事务提交 A3
}
理解解释:
1.spring里面mybatis中的注解管理器只能管到在这个整个spring 容器中注册了的bean,对于字节new出来的目标类的注解是不管的,故同样是调用Test_batch类中的test_batch()方法,只有A1处的注解起作用了;而A3处的注解没有起作用。
2.目标类中,只能是从外部调用过来的地方,带注解的方法才能起作用;内部调用到带注解的方法是不起作用的。所以A1处的注解起作用了;而A2处的注解没有起作用。