Spring--基於註解的aop實現

1首先編寫業務類,如:

@Configuration
public class MathCalculator {
    public int div(int i,int j){
        System.out.println("目標方法正在執行》》》》》》》》》》》》》");
        return i/j;
    }

2.編寫aop類,寫入前置,後置,返回,異常通知的方法,在對應的方法上分別加上相應的註解:

注意,此處會將AOP的相關類和業務類進行關聯,可以用@PointCut切入,也可以直接在各個方法上的註解上直接切入

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;

import java.util.Arrays;

/**
 * @Aspect告訴spring此類是一個切面類
 */
@Aspect
public class LogAspect {


    //抽取公共切入點
    //其他的切面類引用
    //其他切面類引用
    @Pointcut("execution(public int com.example.spring03.aop.MathCalculator.*(..))")
    public void pointCut(){

    }

    @Before("pointCut()")
    public void logStart(JoinPoint joinpoint){
        System.out.println(joinpoint.getSignature().getName()+"開始運行了,參數列表:"+ Arrays.asList(joinpoint.getArgs()));
    }

    @After(value = "pointCut()")
    public void logEnd(JoinPoint joinPoint){
        System.out.println(joinPoint.getSignature().getName()+"運行結束了!");
    }

    @AfterReturning(value = "pointCut()",returning = "result")
    public void logReturn(JoinPoint joinPoint,Object result){
        System.out.println(joinPoint.getSignature().getName()+"運行結束,返回結果:"+result.toString());
    }

    @AfterThrowing(value = "pointCut()",throwing = "exception")
    public void logException(JoinPoint joinPoint,Exception exception){
        System.out.println(joinPoint.getSignature().getName()+"運行出現異常,異常信息:"+exception.toString());
    }

}

3.將aop相關的類和業務類都加入到IOC容器中,並開啓基於註解的AOP模式

import com.example.spring03.aop.LogAspect;
import com.example.spring03.aop.MathCalculator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

/**
 * @EnableAspectJAutoProxy開啓基於註解的AOP模式
 */

@EnableAspectJAutoProxy
@Configuration
public class ConfigOfAop {

    @Bean
    public MathCalculator mathCalculator(){
        return new MathCalculator();
    }

    @Bean
    public LogAspect logAspect(){
        return new LogAspect();
    }


}

4.編寫測試類,此時獲取容器中的業務類的實例,必須通過IOC容器獲取,IOC容器會自動調用相應的AOP方法

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章