Spring - Aspectj开发AOP-注解配置方式

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("最终通知");
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值