AOP 步骤
- 将业务逻辑组件和切面类都加入到容器中,告诉spring哪个是切面类(@Aspect)
- 在切面类上的每一个通知方法上标注通知注解,告诉Spring何时何地运行(切入点表达式)
- 开启基于注解的aop模式: @EnableAspectJAutoProxy
被代理类
package com.ctra.aop;
public class MathCaculator {
public int div(int i ,int j){
System.out.println("执行除法");
return i/j;
}
}
切面类
切面类 LogAspects
package com.ctra.aop;
import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.Bean;
import java.util.ArrayList;
import java.util.Arrays;
// @Aspect:告诉spring,当前类是一个切面
@Aspect
public class LogAspects {
// 抽取公共的切入点表达式
// 1、本类使用 pointCut()
// 2、其他的切面引用
@Pointcut("execution(public int com.ctra.aop.MathCaculator.*(..))")
public void pointCut(){}
// @Before 在目标方法之前切入:切入点表达式(指定在那个方法切入)
// @Before("public int com.ctra.aop.MathCaculator.div(int,int)")
// @Before("public int com.ctra.aop.MathCaculator.*(..)") 第一次优化
@Before("pointCut()") //第二次优化
public void logStart(JoinPoint joinPoint){
Object[] args = joinPoint.getArgs();
System.out.println(joinPoint.getSignature().getName()+"除法运行。。。@Before参数列表是{"+ Arrays.asList(args)+"}");
}
@After("pointCut()")
public void logEnd(JoinPoint joinPoint){
System.out.println(joinPoint.getSignature().getName()+"除法结束。。。@After");
}
// result 正产返回的返回值
@AfterReturning(value = "pointCut()",returning = "result")
public void logReturn(Object result){
System.out.println("除法正常返回。。。 @AfterReturning:运行结果是:{"+result+"}");
}
@AfterThrowing(value = "pointCut()",throwing = "exception")
public void logException(JoinPoint joinPoint,Exception exception){
System.out.println(joinPoint.getSignature().getName()+"除法异常。。。@AfterThrowing异常信息是:{"+exception+"}");
}
}
动态代理类
package com.ctra.config;
/*
AOP 【动态代理】
值在程序运行期间动态的将某段代码切入到指定方法指定位置进行运行的编程方式
1、导入
*/
import com.ctra.aop.LogAspects;
import com.ctra.aop.MathCaculator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableAspectJAutoProxy
public class ConfigAOP {
@Bean
public LogAspects logAspects(){
return new LogAspects();
}
@Bean
public MathCaculator mathCaculator(){
return new MathCaculator();
}
}
测试类
@Test
public void test01(){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConfigAOP.class);
// 1. 不要自己创建对象
// MathCaculator mathCaculator = new MathCaculator();
// mathCaculator.div(1,2);
MathCaculator bean = context.getBean(MathCaculator.class);
bean.div(1,0);
context.close();
}