spring 的环绕通知

环绕增强允许在目标类方法调用前后织入横切逻辑,它 综合实现了前置、后置增强两者的功能。
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
 * @author Chris Yu
 * 
 * @CreateTime 2014-5-12 下午10:25:37
  */
public class GreetingInterceptor implements MethodInterceptor {
/*
 * (非 Javadoc)
 * 
 * 截获目标类方法的执行,并在前后添加横切逻辑
 * 
 * @see
 * org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept
 * .MethodInvocation)
 */
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object[] args = invocation.getArguments();
String clientName = (String) args[0];
// 在目标方法执行前调用
System.out.println("How are you! Mr." + clientName);
// 通过反射机制调用目标方法
Object object = invocation.proceed();
// 在目标方法执行后调用
System.out.println("Please enjoy yourself!");
return object;
}
}
spring 直接使用AOP联盟所定义的MethodInterceptor作为环绕增强的接口。该接口拥有唯一的接口方法Object invoke(MethodInvocation invocation) throws Throwable,MethodInvocation 不但封装目标类方法及其入参数组,还封装了目标方法所在的实例对象,通过Methodinvocation的getArguments()可以获取目标方法的入参数组,通过procced()反射调用目标实例相应的方法。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring AOP中,环绕通知(Around Advice)是一种在目标方法执行前后都可以执行的通知类型。它可以完全控制目标方法的执行过程,包括在目标方法执行前、执行后、抛出异常时执行的逻辑。 环绕通知使用@Around注解来定义,需要在切面(Aspect)类的方法上添加该注解。方法的参数可以包括ProceedingJoinPoint类型的参数,用于控制目标方法的执行。在环绕通知中,我们需要手动调用ProceedingJoinPoint的proceed()方法来触发目标方法的执行。 下面是一个简单的示例: ```java @Aspect @Component public class LoggingAspect { @Around("execution(* com.example.service.*.*(..))") public Object logMethod(ProceedingJoinPoint joinPoint) throws Throwable { // 在目标方法执行前执行的逻辑 System.out.println("Before method: " + joinPoint.getSignature().getName()); // 执行目标方法 Object result = joinPoint.proceed(); // 在目标方法执行后执行的逻辑 System.out.println("After method: " + joinPoint.getSignature().getName()); return result; } } ``` 在上述示例中,@Around注解定义了一个环绕通知方法logMethod,它会拦截com.example.service包下所有类的所有方法。在方法体中,我们可以根据需要编写目标方法执行前、执行后的逻辑,并通过proceed()方法来触发目标方法的执行。最后,我们可以通过return语句返回目标方法的返回值。 需要注意的是,环绕通知中的proceed()方法必须被调用,否则目标方法将不会被执行。同时,环绕通知方法的返回值必须与目标方法的返回值类型一致。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值