@AspectJ注解驱动的切面
使用AspectJ注解来声明通知方法
@Acpect:声明一个切面
@Around:通知方法会将目标方法封装起来
@Before:通知方法会在目标方法调用之前执行
@AfterReturning:通知方法会在目标方法返回后调用
@AfterThrowing:通知方法会在目标方法抛出异常后调用
@Aspect
@Component
public class LogAdvice{
// "自定义"前置通知方法
@Before("com.apesource.aspectJ.MyPointcut.daoInsertMethodPointcut()")
public void methodBefore(JoinPoint joinpoint){
System.out.println("[日志输出]:--------前置通知----------------");
System.out.println("[日志输出]:目标对象"+joinpoint.getTarget());
System.out.println("[日志输出]:目标方法"+joinpoint.getSignature().getName());
System.out.println("[日志输出]:");
}
// "自定义"后置通知方法
@AfterReturning("com.apesource.aspectJ.MyPointcut.daoInsertMethodPointcut()||com.apesource.aspectJ.MyPointcut.daoUpdateMethodPointcut()")
public void methodAfter(JoinPoint joinpoint){
System.out.println("[日志输出]:--------后置通知----------------");
}
}
@Pointcut:声明一个切点
注:配置切点用表达式
expression=“execution(* 类的完全限定名.*方法关键字(方法参数))”
代码示例:
public class MyPointcut {
@Pointcut("execution(* com.apesource.dao.*.*Insert(..))")
public void daoInsertMethodPointcut() {
}
}
使用注解来启用AspectJ自动代理
@EnableAspectJAutoProxy:注册AnnotationAwareAspectJAutoProxyCreator(自动代理工厂)
@Configuration
@ComponentScan
@EnableAspectJAutoProxy
public class AppConfig {
}
总结

AspectJ注解驱动的切面实践:日志拦截与方法调用监控
本文详细介绍了如何使用AspectJ注解在Spring应用中实现切面编程,包括前置(@Before)、后置(@AfterReturning)通知的使用,以及自定义切点(@Pointcut)表达式。通过@AspectJAutoProxy,实现了自动代理并监控方法调用过程。
140

被折叠的 条评论
为什么被折叠?



