Spring中的事务管理器(Aspectj)

xiaoxiao2026-08-10  3

Spring 的AOP确实强大! 但是AOP在实际的工作运用中,无外乎就是权限的验证(当然动态代理模式也可以轻松实现)!日志的处理! 但用的最多的还是事务的管理! 而在Spring中的事务管理又分为:A、编程式事物处理                                                优点:可以精确的控制事物的边界                                                缺点是:实现不是很优雅!因为在每一个需事务管理的业务逻辑中都需要调用 TransactionTemplate  的execute()方 法,导致了业务逻辑和系统业务的交叉!                                               B、声明式事物:采用了AOP优雅的解决了编程式事物的缺点 (在中小型项目中用A比较好,事物处理比较单一;大型项目,事物处理比较多的话,用B比较好) 而我们其实在工作中利用注解的方式还要简单些!所以我利用Aspectj加AOP也解决了编程式事物处理的缺点! 以下是我的测试案例 步骤: 1、配置Spring 的Datasource ,TransactionManager,TransactionTemplate            2、定义标注@interface             3、定义Aspect(@Aspect,@around),定义切入点            4、在Spring中配置Aspect就是配置一个简单ben **************************************************************** package com.lovo.annotation; public class AService {   public void createBook(){    System.out.println(&quot;@@@@@@@@@@@&quot;);   }   public static void main(String[] args) { AService a = (AService)SpringUtil.getContext().getBean(&quot;a&quot;); a.createBook(); } } ***************************************************************************** package com.lovo.annotation; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; /** * 增加书的业务操作方法 * @author Administrator * */ public class BookService { //事物模板 private TransactionTemplate trans; //数据源 private DataSource dataSource; public TransactionTemplate getTrans() {   return trans; } public void setTrans(TransactionTemplate trans) {   this.trans = trans; } public DataSource getDataSource() {   return dataSource; } public void setDataSource(DataSource dataSource) {   this.dataSource = dataSource; } //添加事物属性值 @Trans(TransactionTemplate.PROPAGATION_REQUIRED) /**   * 业务方法   */     public void createBook(){   //创建jdbc模板      JdbcTemplate jdbc = new JdbcTemplate(dataSource);      //执行插入数据库操作      jdbc.update(&quot;insert into T_BOOK values(5522,'Spring3 in Action',3)&quot;);          } } ******************************************************************************* package com.lovo.annotation; /** * 测试类 * @author Administrator * */ public class Client {   public static void main(String[] args) { BookService bookServ = (BookService)SpringUtil.getContext().getBean(&quot;bookService&quot;); bookServ.createBook();   } } ************************************************************************* package com.lovo.annotation; /** * 定义一个注释类 */ import java.lang.annotation.Target; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.ElementType; @Target({ElementType.METHOD}) @Retention(RUNTIME) public @interface Trans { int value(); } ********************************************************************** package com.lovo.annotation; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * 定义一个加载配置文件的单例工具类。 * * @author Administrator * */ public class SpringUtil { private SpringUtil(){   }   private static ApplicationContext context = new ClassPathXmlApplicationContext(&quot;applicationContext.xml&quot;);   public static ApplicationContext getContext(){    return context;   } } ************************************************************** package com.lovo.annotation; import java.lang.reflect.Method; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; @Aspect public class TransactionAspect {    // 拦截对目标对象方法调用  @Around(&quot;execution(@com.lovo.annotation.Trans * *.*(..))&quot;) public Object inTransaction(final ProceedingJoinPoint pjp) {   //获得事物模板         TransactionTemplate trans = (TransactionTemplate)SpringUtil.getContext().getBean(&quot;transactionTemplate&quot;);         // 获取连接点的方法签名对象         MethodSignature sig = (MethodSignature) pjp.getSignature();         // 连接点对象的方法     Method method = sig.getMethod();         // 返回@trans的注释对象    Trans antrans = (Trans) method.getAnnotation(Trans.class);   //设定事物的属性值   trans.setPropagationBehavior(antrans.value());     //执行事务的方法         return trans.execute(new TransactionCallback(){    public Object doInTransaction(TransactionStatus ts) {     Object result = null;     try {      result=pjp.proceed();     } catch (Throwable e) {      ts.setRollbackOnly();      e.printStackTrace();     }     return result;    }                  });   } } *************************************************************************** 配置文件 <?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"               xsi:schemaLocation=                           "http://www.springframework.org/schema/beans                            http://www.springframework.org/schema/beans/spring-beans.xsd                            http://www.springframework.org/schema/aop                            http://www.springframework.org/schema/aop/spring-aop.xsd"> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">   <property name="transactionManager">    <ref bean="transactionManager"/>   </property> </bean> <bean id="transactionManager"        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">       <property name="dataSource">         <ref local="dataSource"/>       </property>       </bean> <bean id="dataSource"        class="org.springframework.jdbc.datasource.DriverManagerDataSource">       <property name="driverClassName">         <value>oracle.jdbc.driver.OracleDriver</value>       </property>       <property name="url">         <value>jdbc:oracle:thin:@localhost:1521:ORCL</value>       </property>       <property name="username"><value>scott</value></property>       <property name="password"><value>wl</value></property> </bean> <bean id="bookService" class="com.lovo.annotation.BookService">   <property name="dataSource">     <ref bean="dataSource"/>   </property>   <property name="trans">     <ref bean="transactionTemplate"/>   </property>   </bean>   <bean id="transAspect" class="com.lovo.annotation.TransactionAspect"></bean> </beans>

相关资源:Java 面经手册·小傅哥(公众号:bugstack虫洞栈).pdf
转载请注明原文地址: https://www.6miu.com/read-5050993.html

最新回复(0)