首頁  >  文章  >  Java  >  Java Spring之基於註解的AOP怎麼配置

Java Spring之基於註解的AOP怎麼配置

PHPz
PHPz轉載
2023-05-17 17:37:061017瀏覽

    1 環境建構

    1.1 第一步:準備必要的程式碼和jar 套件

    • 拷貝上一小節的工程即可。

    1.2 第二步:在設定檔中匯入context 的名稱空間

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        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
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
     
        <!-- 配置数据库操作对象 -->
        <bean id="dbAssit" class="com.itheima.dbassit.DBAssit">
            <property name="dataSource" ref="dataSource"></property>
            
            <!-- 指定 connection 和线程绑定 -->
            <property name="useCurrentConnection" value="true"></property>
        </bean>
     
        <!-- 配置数据源 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql:///spring_day02"></property>
            <property name="user" value="root"></property>
            <property name="password" value="1234"></property>
        </bean>
    </beans>

    1.3 步驟三:把資源使用註解設定

    • #帳戶的業務層實作類別

    @Service("accountService")
    public class AccountServiceImpl implements IAccountService {
     
        @Autowired
        private IAccountDao accountDao;
    }
    • #帳號的持久層實作類別

    @Repository("accountDao")
    public class AccountDaoImpl implements IAccountDao {
        @Autowired
        private DBAssit dbAssit ;
    }

     1.4第四步:在設定檔中指定spring 要掃描的套件

    <!-- 告知 spring,在创建容器时要扫描的包 -->
    <context:component-scan base-package="com.itheima"></context:component-scan>

    2 設定步驟

    2.1 第一步:把通知類別也使用註解設定

    • #事務控制類別

    @Component("txManager")
    public class TransactionManager {
     
        //定义一个 DBAssit
        @Autowired
        private DBAssit dbAssit ;
    }

    2.2 第二步:在通知類別上使用@Aspect 註解宣告為切面

    • 作用:

      • 把目前類別宣告為切面類別。

    • 交易控制類別

    @Component("txManager")
    @Aspect//表明当前类是一个切面类
    public class TransactionManager {
     
        //定义一个 DBAssit
        @Autowired
        private DBAssit dbAssit ;
    }

    2.3 第三個步驟:在增強的方法上使用註解配置通知

    2.3.1 @Before
    • 作用:

      • #把目前方法看成是前置通知。

    • 屬性:

      • value:用於指定切入點表達式,也可以指定切入點表達式的引用。

    //开启事务
    @Before("execution(* com.itheima.service.impl.*.*(..))")
    public void beginTransaction() {
     
        try {
            dbAssit.getCurrentConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    2.3.2 @AfterReturning
    • #作用:

      • #把目前方法看成是後置通知。

    • 屬性:

      • value:用於指定切入點表達式,也可以指定切入點表達式的引用

    //提交事务
    @AfterReturning("execution(* com.itheima.service.impl.*.*(..))")
    public void commit() {
     
        try {
            dbAssit.getCurrentConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    2.3.3 @AfterThrowing
    • 作用:

      • #把目前方法看成是異常通知。

    • 屬性:

      • value:用於指定切入點表達式,也可以指定切入點表達式的引用

    //回滚事务
    @AfterThrowing("execution(* com.itheima.service.impl.*.*(..))")
    public void rollback() {
     
        try {
            dbAssit.getCurrentConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    2.3.4 @After
    • 作用:

      #把目前方法看成是最終通知。

    屬性:
    • value:用於指定切入點表達式,也可以指定切入點表達式的引用
      • //释放资源
        @After("execution(* com.itheima.service.impl.*.*(..))")
        public void release() {
         
            try {
                dbAssit.releaseConnection();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
      • 2.4 第四步:在spring 設定檔中開啟spring 對註解AOP 的支援
      <!-- 开启 spring 对注解 AOP 的支持 -->
      <aop:aspectj-autoproxy/>
    • 3 環繞通知註解設定@Around

      • 作用:
      把目前方法看成是環繞通知。

    • 屬性:

      • value:用於指定切入點表達式,也可以指定切入點表達式的引用。

      /**
      * 环绕通知
      * @param pjp
      * @return
      */
      @Around("execution(* com.itheima.service.impl.*.*(..))")
      public Object transactionAround(ProceedingJoinPoint pjp) {
       
          //定义返回值
          Object rtValue = null;
       
          try {
          
              //获取方法执行所需的参数
              Object[] args = pjp.getArgs();
          
              //前置通知:开启事务
              beginTransaction();
       
              //执行方法
              rtValue = pjp.proceed(args);
       
              //后置通知:提交事务
              commit();
              }catch(Throwable e) {
       
              //异常通知:回滚事务
              rollback();
              e.printStackTrace();
          }finally {
       
          //最终通知:释放资源
          release();
          }
       
          return rtValue;
      }
    • 4 切入點表達式註解 @Pointcut

      • 作用:
      指定切入點表達式

    #######屬性:###############value:指定表達式的內容### #########
    @Pointcut("execution(* com.itheima.service.impl.*.*(..))")
    private void pt1() {}
     
        /**
        * 引用方式:
        * 环绕通知
        * @param pjp
        * @return
        */
        @Around("pt1()")//注意:千万别忘了写括号
        public Object transactionAround(ProceedingJoinPoint pjp) {
     
        //定义返回值
        Object rtValue = null;
     
        try {
            //获取方法执行所需的参数
            Object[] args = pjp.getArgs();
     
            //前置通知:开启事务
            beginTransaction();
            
            //执行方法
            rtValue = pjp.proceed(args);
     
            //后置通知:提交事务
            commit();
        }catch(Throwable e) {
     
            //异常通知:回滚事务
            rollback();
            e.printStackTrace();
        }finally {
     
            //最终通知:释放资源
            release();
        }
        
        return rtValue;
    }
    ###5 不使用XML 的設定方式###
    @Configuration
    @ComponentScan(basePackages="com.itheima")
    @EnableAspectJAutoProxy
    public class SpringConfiguration {
     
    }

    以上是Java Spring之基於註解的AOP怎麼配置的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    陳述:
    本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除