AOPは、カスタム注釈のためのパラメータ値を取得しました

ディレクトリ

1、AOPの基本的なプロセスを実現するためのアノテーションの使用

  1.1、コメント接線ポイント(ポイントカット)のためのメモを作成します

  1.2、カットポイントを指定するアノテーションを使用して上記で定義され、サービスを作成します

  1.3、アスペクトを作成し、ビジネス・ロジックを増やします

  1.4、Spring構成クラスを作成します

  1.5 テスト

2、カスタムパラメータの注釈を取得します  

 

春、AOPは、次の簡単な例として、カスタム注釈の方法によって達成することができます。

 

1.1コメントタンジェントポイント(ポイントカット)のためのメモを作成します

パッケージcn.ganlixin.annotation。

輸入java.lang.annotation.ElementType。
輸入java.lang.annotation.Retention。
輸入java.lang.annotation.RetentionPolicy。
輸入java.lang.annotation.Target; 

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
パブリック@interfaceのDemoAnnotation { 
    //注意这里没有定义属性
}

  

1.2、カットポイントを指定するアノテーションを使用して上記で定義され、サービスを作成します

  ここでは、サービス・インターフェースを作成し、インターフェイスを実装するserviceImplを作成し、サービスに直接書いていない、スペースを節約するために:

;パッケージcn.ganlixin.service 

インポートcn.ganlixin.annotation.DemoAnnotation; 
インポートorg.springframework.stereotype.Service; 

@Service 
パブリッククラスDemoService { 

    @DemoAnnotation //カスタム注釈を使用し、この方法は、カットオフポイント法として宣言され
    ます。public voidデモ(){ 
        System.out.printlnは( "DemoService.demoこれは()が"); 
    } 
}

  

1.3、アスペクトを作成し、ビジネス・ロジックを増やします

パッケージcn.ganlixin.aspect。

輸入org.aspectj.lang.annotation.Aspect; 
輸入org.aspectj.lang.annotation.Before; 
輸入org.springframework.stereotype.Component。

@Component 
@Aspect 
パブリッククラスDemoAspect { 

    @Before( "@アノテーション(cn.ganlixin.annotation.DemoAnnotation)")
    公共ボイドdemoBefore(){ 
        System.out.printlnは( "これは、出力メッセージの前にあります")。
    } 
}

  

1.4、Spring構成クラスを作成します

  主にそれがあるん:パッケージのスキャン・パスを指定します。

パッケージcn.ganlixin。

輸入org.springframework.context.annotation.ComponentScan; 
輸入org.springframework.context.annotation.Configuration。
輸入org.springframework.context.annotation.EnableAspectJAutoProxy; 

@Configuration 
@ComponentScan( "cn.ganlixin")
@EnableAspectJAutoProxy 
パブリッククラスのAppConfig { 
    
}

  

1.5テスト

パッケージcn.ganlixin。

輸入cn.ganlixin.service.DemoService; 
輸入org.junit.Test; 
輸入org.springframework.context.ApplicationContext; 
輸入org.springframework.context.annotation.AnnotationConfigApplicationContext; 

パブリッククラスAppTest { 

    @Test 
    公共ボイドtestAOP1(){ 
        ApplicationContextのコンテキスト=新しいAnnotationConfigApplicationContext(AppConfig.class)。

        DemoService demoService = context.getBean(DemoService.class)。
        demoService.demo(); 
    } 
}

  出力:

これは、出力メッセージの前にある
)(これはDemoService.demoです

  

 

おすすめ

転載: www.cnblogs.com/-beyond/p/11387487.html