AspectJ使用例

24031 ワード

一、SpringでAspectJ注釈サポートを有効にする
1 SpringアプリケーションでAspectJ注釈を使用するには、classpathの下にAspectJクラスライブラリ:aopalliance.jar、aspectj.weaver.jar、spring-aspects.jar maven導入
<dependency>
<groupId>org.springframeworkgroupId>  
<artifactId>spring-aopartifactId>  
<version>4.1.9.RELEASEversion>  
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>4.1.9.RELEASEversion>
dependency>
<dependency>
<groupId>org.aspectjgroupId>  
<artifactId>aspectjrtartifactId>  
<version>1.6.8version>  
dependency>  
<dependency>  
<groupId>org.aspectjgroupId>  
<artifactId>aspectjweaverartifactId>  
<version>1.6.8version>  
<scope>runtimescope>  
dependency>    
を含める必要があります.
2 aop Schemaを ルート要素のうち.3 Spring IOCコンテナでAspectJ注釈サポートを有効にするには、Beanプロファイルに空のXML要素
<aop:aspectj-autoproxy>aop:aspectj-autoproxy>  
を定義します.
4 Spring IOCコンテナがBeanプロファイルの 要素の場合、AspectJ断面に一致するBeanのプロキシが自動的に作成されます.二、AspectJは5種類の通知注記をサポートする.
@Before:メソッドの実行前にを実行する前置き通知
@After:後置通知、メソッド実行後を実行
@AfterRunning:メソッドが結果を返す後にを実行する通知を返します.
@AfterThrowing:異常通知、メソッドが異常を放出した後@Around:オービット通知、メソッドをめぐってを実行
2.1.以前の計算機インタフェースと実装クラスArithmeticCalculator.java,ArithmeticCalculatorImpl.javaを使用する
@Component("arithmeticCalculator")
public class ArithmeticCalculatorImpl implements ArithmeticCalculator{}  

2.2、xmlにスキャン注記とaspectjのサポートを追加する

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
        
    
    <context:component-scan base-package="com.hp.spring.aop.annotation">context:component-scan>
    
    
    <aop:aspectj-autoproxy>aop:aspectj-autoproxy>
beans>  

2.3.切面類を作成し、各種通知を定義する
@Aspect //      
@Component
public class LoggingAspect {
    //    
    @Before("execution(public int com.hp.spring.aop.annatation.ArithmeticCalculator.*(int, int))")
    public void beforeMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        Object [] args = joinPoint.getArgs();
        
        System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));
    }
    //    
    @After("execution(* com.hp.spring.aop.annatation.*.*(..))")
    public void afterMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " ends");
    }
    
}  

@before @afterの式と同じなのでspringは式を抽出する方法をサポートし、抽出後のコードは以下の通りです.
package com.hp.spring.aop.annotation;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
 *      @Order           ,         
 */
@Order(2) 
@Aspect
@Component
public class LoggingAspect {
    
    /**
     *       ,           .    ,                . 
     *    @Pointcut          . 
     *                           . 
     */
    @Pointcut("execution(public int com.hp.spring.aop.annotation.ArithmeticCalculator.*(..))")
    public void declareJointPointExpression(){}
    
    /**
     *   com.hp.spring.aop.annotation.ArithmeticCalculator                          
     */
    @Before("declareJointPointExpression()")
    public void beforeMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        Object [] args = joinPoint.getArgs();
        
        System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));
    }
    
    /**
     *             .            
     */
    @After("declareJointPointExpression()")
    public void afterMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " ends");
    }
    
    /**
     *               
     *                  !
     */
    @AfterReturning(value="declareJointPointExpression()",
            returning="result")
    public void afterReturning(JoinPoint joinPoint, Object result){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " ends with " + result);
    }
    
    /**
     *                 .
     *          ;                     
     */
    @AfterThrowing(value="declareJointPointExpression()",
            throwing="e")
    public void afterThrowing(JoinPoint joinPoint, Exception e){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " occurs excetion:" + e);
    }
    
    /**
     *          ProceedingJoinPoint      . 
     *                : ProceedingJoinPoint                  .
     *            ,              
     */
    /*
    @Around("execution(public int com.hp.spring.aop.annotation.ArithmeticCalculator.*(..))")
    public Object aroundMethod(ProceedingJoinPoint pjd){
        
        Object result = null;
        String methodName = pjd.getSignature().getName();
        
        try {
            //    
            System.out.println("The method " + methodName + " begins with " + Arrays.asList(pjd.getArgs()));
            //      
            result = pjd.proceed();
            //    
            System.out.println("The method " + methodName + " ends with " + result);
        } catch (Throwable e) {
            //    
            System.out.println("The method " + methodName + " occurs exception:" + e);
            throw new RuntimeException(e);
        }
        //    
        System.out.println("The method " + methodName + " ends");
        
        return result;
    }
    */
}

切面二
package com.hp.spring.aop.annotation;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Order(1)
@Aspect
@Component
public class VlidationAspect {
    @Before("com.hp.spring.aop.annotation.LoggingAspect.declareJointPointExpression()")
    public void validateArgs(JoinPoint joinPoint){
        System.out.println("-->validate:" + Arrays.asList(joinPoint.getArgs()));
    }
    
}

テストクラス
package com.hp.spring.aop.annotation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
    
    public static void main(String[] args) {
        
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-aspectj.xml");
        ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator");
        
        System.out.println(arithmeticCalculator.getClass().getName());
        
        int result = arithmeticCalculator.add(1, 2);
        System.out.println("result:" + result);
        
        result = arithmeticCalculator.div(1000, 10);
        System.out.println("result:" + result);
    }
    
}

印刷:com.sun.proxy.$Proxy 12-->validate:[1,2]The method add begins with[1,2]The method add ends The method add ends with 3 result:3-->validate:[100,10]The method div begins with[100,10]The method div ends The method div div ends with 100 result:100
印刷されたログでは、ダイナミックエージェントと同様に、さまざまな通知を定義できることがわかります.