Aspectj提供的Advice类型
AspectJ提供不同的通知类型:
Before (前置通知),相当于BeforeAdvice
AfterReturning (后置通知),相当于AfterReturningAdvice
Around (环绕通知),相当于MethodInterceptor
AfterThrowing(抛出通知),相当于ThrowAdvice
After (最终final通知),不管是否异常,该通知都会执行
DeclareParents (引介通知),相当于IntroductionInterceptor
XML中配置:
<!-- 开启注解扫描
base-package:要扫描的包及其子包
-->
<context:component-scan base-package="com.XXX"></context:component-scan>
<!--
配置aop的aspectj的自动代理:
自动扫描bean组件中,含有@Aspect的bean,将其作为aop管理, 开启动态代理
-->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
切面类:
@Component
@Aspect
public class MyAspect {
@Pointcut("bean(*ServiceImpl)")
public void method() {
}
@Before(value = "method()")
public void beforeAdvice(JoinPoint joinPoint) {
System.out.println("前置通知");
System.out.println("方法名称:" + joinPoint.getSignature().getName());
System.out.println("方法参数:" + joinPoint.getArgs());
System.out.println("目标对象:" + joinPoint.getTarget().getClass().getName());
System.out.println("代理对象:" + joinPoint.getThis().getClass().getName());
System.out.println("==================================");
}
@AfterReturning(value = "method()", returning = "returnVal")
public void afterAdvice(JoinPoint joinPoint, Object returnVal) {
System.out.println("后置通知");
System.out.println("方法名称:" + joinPoint.getSignature().getName());
System.out.println("方法参数:" + joinPoint.getArgs());
System.out.println("返回值:" + returnVal);
System.out.println("目标对象:" + joinPoint.getTarget().getClass().getName());
System.out.println("代理对象:" + joinPoint.getThis().getClass().getName());
}
@Around(value = "method()")
public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕通知前置部分");
// 调用目标方法
Object result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
System.out.println("环绕通知的后置部分");
// 这里可以修改最终方法的最终返回值!
return result;
}
@AfterThrowing(value = "method()", throwing = "ex")
public void afterThrowingAdvice(JoinPoint joinPoint, Throwable ex) {
System.out.println("异常信息:" + ex.getMessage());
}
@After(value = "method()")
public void finallyAdvice(JoinPoint joinPoint) {
System.out.println("最终通知");
}
}