1、基础介绍
只在程序运行期间动态的将代码切入到指定方法位置进行运行的方法
1、导入aop组件Spring aop (spring-aspects)
2、定义一个业务逻辑类;运行的时候打印日志(运行之前,运行之后,出现异常)
3、定义一个日志切面类,切面里面动态感知业务逻辑类运行到哪一步
通知方法:
前置通知(@Before):logStart:在目标方法运行之前
后置通知(@After):logEnd:在目标方法运行之后
返回通知(@AfterReturning):logReturn:在目标方法返回之后
异常通知(@AfterException):logException:在目标方法异常之后
环绕通知:动态代理
4、给切面类的目标方法标注何时运行
5、将切面和业务类加入容器里
6、必须告诉Spring哪个类是切面类
7、给配置类加@EnableAspectJAutoProxy,开启基于注解的aop的模式
- 业务类:Muti
public class Muti {
public int mut(int a, int b) {
System.out.println("mut");
return a/b;
}
}
- 切面类:LogAspects
// 告诉Spring当前类是切面类
@Aspect
public class LogAspects {
// 抽取刚刚的切入点表达式
@Pointcut("execution(public int com.dav.aop.Muti.*(..))")
public void Pointcut() {
}
// JoinPoint一定要出现在第一个,否则会报错
@Before("Pointcut()")
public void logStart(JoinPoint joinPoint) {
System.out.println(joinPoint.getSignature().getName() + "-start-" + Arrays.asList(joinPoint.getArgs()));
}
@After("Pointcut()")
public void logEnd() {
System.out.println("end");
}
@AfterReturning(value = "Pointcut()", returning = "result")
public void logRetrun(Object result) {
System.out.println("return" + result);
}
@AfterThrowing(value = "Pointcut()", throwing = "e")
public void logException(Exception e) {
System.out.println("exception" + e.getMessage());
}
}
- 配置类:MainConfigOfAop
@EnableAspectJAutoProxy
@Configuration
public class MainConfigOfAop {
@Bean
public Muti muti() {
return new Muti();
}
@Bean
public LogAspects logAspects() {
return new LogAspects();
}
}
- 测试类:
@Test
public void test1() {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(MainConfigOfAop.class);
Muti muti = context.getBean(Muti.class);
muti.mut(1, 0);
context.close();
}