Spring 下事务管理-使用AOP Transactional注解管理

               

 Spring 下事务管理-使用AOP @Transactional注解管理

        除了使用 XML 配置管理之外,AOP 还有一种事务管理的方式:使用 @Transactional 注解事务管理。
        其中的类定义:

<!-- the service class that we want to make transactional -->@Transactionalpublic class PurchaseServiceImpl implements PurchaseService {    Foo getFoo(String fooName);    Foo getFoo(String fooName, String barName);    void insertFoo(Foo foo);    void updateFoo(Foo foo);}



        当上述的 POJO 定义在 Spring IoC 容器里时,上述 bean 实例仅仅通过一行 xml 配置就可以使它具有事务性的。如下:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:aop="http://www.springframework.org/schema/aop"       xmlns:tx="http://www.springframework.org/schema/tx"       xsi:schemaLocation="       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">  <!-- this is the service object that we want to make transactional -->  <bean id="purchaseService" class="com.defonds.netbuy.purchase.service.PurchaseServiceImpl"/>  <!-- enable the configuration of transactional behavior based on annotations -->  <tx:annotation-driven transaction-manager="txManager"/>  <!-- a PlatformTransactionManager is still required -->  <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">    <!-- (this dependency is defined somewhere else) -->    <property name="dataSource" ref="dataSource"/>  </bean>  <!-- other <bean/> definitions here -->  </beans>



        如果是 iBatis 框架,可以参考上篇博客《Spring 下事务管理 - 使用 AOP XML 配置管理(iBatis 为例)》里的相关 dao 支持。
        @Transactional 注解应该只被应用到 public 可见度的方法上。 如果你在 protected、private 或者 package-visible 的方法上使用 @Transactional 注解,它也不会报错, 但是这个被注解的方法将不会展示已配置的事务设置。
        @Transactional 注解可以被应用于接口定义和接口方法、类定义和类的 public 方法上。然而,请注意仅仅 @Transactional 注解的出现不足于开启事务行为,它仅仅 是一种元数据,能够被可以识别 @Transactional 注解和上述的配置适当的具有事务行为的beans所使用。上面的例子中,其实正是 <tx:annotation-driven/>元素的出现 开启 了事务行为。
        Spring团队的建议是你在具体的类(或类的方法)上使用 @Transactional 注解,而不要使用在类所要实现的任何接口上。你当然可以在接口上使用 @Transactional 注解,但是这将只能当你设置了基于接口的代理时它才生效。因为注解是 不能继承 的,这就意味着如果你正在使用基于类的代理时,那么事务的设置将不能被基于类的代理所识别,而且对象也将不会被事务代理所包装(将被确认为严重的)。因此,请接受Spring团队的建议并且在具体的类上使用 @Transactional 注解。
参考文献:《Spring Framework reference 2.0.5》。

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/hgguhff/article/details/86507461