AOP(动态代理):指在程序运行期间,动态的将某段代码切入到指定方法指定位置进行运行的编程方式。
1.导入AOP模块,Spring-aspects,如添加对应的maven依赖
2.定义个业务逻辑类(Calculator.java),在业务逻辑运行的时候将日志打印(方法运行前、运行后、返回值、抛异常)。
3.定义一个切面类(LogAspectj):切面类里面的方法需要动态感知Calculator.div运行到哪里然后执行。
通知方法:
前置通知(@Before):logStart.在目标方法div运行之前执行
后置通知(@After):logEnd.在目标方法div运行之后执行(无论是否抛异常,都会执行)
返回通知(@AfterReturning):logReturn.在目标方法div正常返回之后执行
异常通知(@AfterThrowing):logException.在目标方法div出现异常以后执行
环绕通知(@Around):动态代理,手动推进目标方法执行(joinPoint.procced())
4.给切面类中的方法定义何时何地运行(标注通知注解)
5.将切面类和业务逻辑类(目标方法所在类)都要加入到容器中,只有交给容器管理的bean,才能使用spring的功能
6.必须告诉容器,哪个是切面类(标注上@Aspect注解,表示当前类是个切面类)
7.给主配置类加上@EnableAspectJAutoProxy,开启基于注解的AOP模式
理论到此,上代码
主配置类
package com.my.config;
import com.my.beans.Calculator;
import com.my.beans.LogAspectj;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableAspectJAutoProxy
public class MainConfigofAOP {
@Bean
public Calculator calculator(){
return new Calculator();
}
@Bean
public LogAspectj logAspectj(){
return new LogAspectj();
}
}
业务逻辑类Calculator.java
package com.my.beans;
public class Calculator {
public int div(int i ,int j){
System.out.println("逻辑方法执行。。。。。");
return i/j;
}
}
切面类LogAspectj.java
package com.my.beans;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import java.util.Arrays;
@Aspect
public class LogAspectj {
@Before("execution(public int com.my.beans.Calculator.*(..))")
public void logStart(JoinPoint joinPoint){
System.out.println(joinPoint.getSignature().getName()+"方法开始执行。。。参数列表为:"+ Arrays.asList(joinPoint.getArgs()));
}
@After("execution(public int com.my.beans.Calculator.*(..))")
public void logEnd(JoinPoint joinPoint){
System.out.println(joinPoint.getSignature().getName()+"方法执行结束。。。");
}
@AfterReturning(value = "execution(public int com.my.beans.Calculator.*(..))",returning = "result")
public void logReturn(JoinPoint joinPoint,Object result){
System.out.println(joinPoint.getSignature().getName()+"方法返回值为:"+result);
}
@AfterThrowing(value = "execution(public int com.my.beans.Calculator.*(..))",throwing = "exception")
public void logException(JoinPoint joinPoint,Exception exception ){
System.out.println(joinPoint.getSignature().getName()+"方法报错,错误信息为:"+exception);
}
}
测试类
package com.my.test;
import com.my.beans.Calculator;
import com.my.config.MainConfigofAOP;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class AOP_test {
@Test
public void test01(){
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfigofAOP.class);
Calculator calculator = (Calculator) context.getBean("calculator");
calculator.div(1,0);
}
}