创建切面类(事务管理)
操作数据库的数据源应该从切面类中产生
不用传递参数的方法,采用第三方中介(切面类产生数据源给中介,中介dao层直接调中介的数据源)
因为这个中介算工具类,所以数据源属性必然是static修饰,是一块公共共享空间
这样会造成多线程情况下(你用切面类我也用切面类产生数据源,公共空间就一块,第二个人覆盖第一个人的情况)
解决:线程对象
两个get数据源:
在非目标对象(没有标注解的方法)中,无法获取数据源,因为没走切面类,所以在中介那再设置一种情况,但数据源为空时
整个新的给这个方法,但此时已经跟切面类没有任何关系了
塞的这个新数据源1.不能是静态,因为静态不能用@Resource
2.不能不是静态,不然在静态方法调不成
非静态可以调静态
所以:将新数据源提升为静态 创建set方法,注@Resource
注解事务
通常放进service层中,组合dao层方法返回数据到controller.
只有运行时异常会触发回滚,编译时异常需要其他操作(可以抛出一个运行时异常,分情况)
事务也要依赖于datasource。关键属性必须要注入
1.首先在spring.xml中注册事务管理器对象
<!--事务管理器对象,id必须是transactionManager,此对象必须依赖DataSource-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
2.加上事务注解识别
<!--事务注解识别:@Transactional,事务切面中默认获取id=transactionManager的事务管理器对象-->
<tx:annotation-driven></tx:annotation-driven>
3.在方法上(通常是service层)加上注解@transaction
@Transactional
public Integer addTwoEmp(Emp e,Emp e2) {
hm.addEmp(e);
Integer integer = hm.addEmp(e2);
return integer;
}
xml文件配置事务
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"></tx:method>
<tx:method name="select*" propagation="SUPPORTS"></tx:method>
<tx:method name="get*" propagation="SUPPORTS"></tx:method>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.javasm.*.service.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"></aop:advisor>
</aop:config>