春AOPの使用

AOPは:アスペクト指向プログラミング、アスペクト指向プログラミングの略

春AOPの役割と利点:

  1. 役割:プログラムの実行時には、既存の方法を強化するためにソースコードを変更しません
  2. 利点:コードの重複を減らす、開発効率を向上させ、メンテナンスが容易

春AOPの実装:

  1. Javaを使用して、動的エージェント技術
  2. ウェイ構成で

春AOP関連用語:

  1. ジョインポイント(接続点):これらの点に傍受。のみスプリング型接続点は、メソッドをサポートするので、春に、これらの点は、方法を指します。
  2. ポイントカット(エントリポイント):私たちはジョインポイントのインターセプトを定義したいということ。
  3. アドバイス(通知/エンハンスド):迎撃を行うためにoinpointの事を指した後は、通知することです。通知の種類:アドバイスの周りに通知フロント、リアの通知、異常通知、最後の通知、。

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="accountService" class="com.lin.service.impl.AccountServiceImpl"/>

    <!--spring中基于XML的AOP配置步骤
        1、把通知Bean也交给spring来管理
        2、使用aop:config标签表明开始AOP的配置:
        3、使用aop:aspect标签表明配置切面
                id属性:是给切面提供一个唯一表示
                ref属性:是指定通知类bean的Id
        4、在aop:aspect标签的内部使用对应标签来配置通知的类型
            这里示例是让printLog方法在切入点方法执行之前:所以是前置通知
            aop:before:表示配置前置通知
                method属性:用于指定Logger类中哪个方法是前置通知
                pointcut属性:用于指定切入点表达式,指对业务层中哪些方法增强
            切入点表达式的写法:
                关键字:execution(表达式)
                表达式:
                    访问修饰符   返回值 包名.包名...类名.方法名(参数列表)
                标准表达式写法:
                    public void com.lin.service.impl.AccountServiceImpl.saveAccount()
    -->
    <bean id="logger" class="com.lin.util.Logger"/>
    <aop:config>
        <aop:aspect id="logAdvice" ref="logger">
            <aop:pointcut id="pt1" expression="execution(public void com.lin.service.impl.AccountServiceImpl.saveAccount())"/>
            <aop:before method="printLog"
                        pointcut-ref="pt1"/>
        </aop:aspect>
    </aop:config>

</beans>

注釈を使用して設定するとき、次のような構成です。

  1. xmlファイルのオープンAOP注:

        <!--开启spring注解AOP支持-->
        <aop:aspectj-autoproxy/>
  2. 次のようにクラスに注釈を付け:

    /**
     * 用于记录日志的工具,提供公共代码
     * Create by ljc on 2019/11/2
     */
    
    @Component("logger")
    @Aspect //表示当前类是一个切面类
    public class Logger
    {
        @Pointcut("execution(* com.lin.service.impl.*.*(..))")
        private void pt1()
        {
        }
    
    
        @Before("pt1()")
        public void beforePrintLog()
        {
            System.out.println("前置通知Logger类中的printLog方法开始记录日志....");
        }
    
        @After("pt1()")
        public void afterPrintLog()
        {
            System.out.println("后置通知Logger类中的printLog方法开始记录日志....");
        }
    
    }

おすすめ

転載: www.cnblogs.com/jinchengll/p/11783347.html