1、AOP
1.1、开启自动代理功能
- 在java配置类上添加注解@EnableAspectJAutoProxy
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(value = "com.xyulu"
,excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class})})
public class AopConfig {
}
1.2、定义切面类
@Component
@Aspect
public class LogAspects {
}
1.3、定义切点
@Pointcut(value = "execution(* com.xyulu..*(..))")
public void pointCut() {
}
1.4、定义通知
- @Before:在目标方法执行前执行通知;
- @After:在目标方法执行后执行通知;
- @AfterReturning:在目标方法执行完成后执行通知;
- @AfterThrowing:在目标方法抛出异常后执行通知;
- @Around:可在目标方法执行前后自定义通知行为;
切点表达式
图片摘自https://blog.csdn.net/longyanchen/article/details/94486678
代码示例
@Pointcut(value = "execution(* com.xyulu..*(..))")
public void pointCut() {
}
@Before(value = "pointCut()")
public void before(JoinPoint joinPoint) {
System.out.println("@Before,方法名:"+joinPoint.getSignature().getName()+",参数:"+ Arrays.asList(joinPoint.getArgs()));
}
@After(value = "pointCut()")
public void after(JoinPoint joinPoint) {
System.out.println("@After,方法名:"+joinPoint.getSignature().getName());
}
@AfterReturning(value = "pointCut()",returning = "result")
public void afterReturn(Object result) {
System.out.println("运行成功,@AfterReturning:"+result);
}
@AfterThrowing(value = "pointCut()",throwing = "exception")
public void exception(Exception exception) {
System.out.println("@AfterThrowing,error is:{}");
}
|