@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 {
}