aop的两种配置方法
一、实现接口并重写方法
实现org.aopalliance.intercept.MethodInterceptor接口,这是AOP Alliance规范中的接口,Spring AOP支持它。这种方式比较适合需要非常细粒度控制的场景。
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class LoggingInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("Before method: " + invocation.getMethod().getName());
try {
Object result = invocation.proceed(); // 继续执行被拦截的方法
return result;
} finally {
System.out.println("After method: " + invocation.getMethod().getName());
}
}
}
在spring配置中,将此拦截器注册到切面中
<aop:config>
<aop:aspect id="loggingAspect" ref="loggingInterceptor">
<aop:pointcut id="serviceMethods" expression="execution(* com.example.service.*.*(..))"/>
<aop:around method="invoke" pointcut-ref="serviceMethods"/>
</aop:aspect>
</aop:config>
<bean id="loggingInterceptor" class="com.example.aspect.LoggingInterceptor"/>
二、通过注解方式(以环绕通知为例)
@Aspect
@Component
public class LoggingAspect {
@Around("execution(* com.example.service.*.*(..))")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("Before method: " + joinPoint.getSignature().getName());
try {
Object result = joinPoint.proceed();
return result;
} finally {
System.out.println("After method: " + joinPoint.getSignature().getName());
}
}
}