一、实现接口并重写方法
实现org.aopalliance.intercept.MethodInterceptor接口,这是AOP Alliance规范中的接口,Spring AOP支持它。这种方式比较适合需要非常细粒度控制的场景。
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;public class LoggingInterceptor implements MethodInterceptor {@Overridepublic 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());}}
}
注意点:确保在配置类(root容器的配置类)上启用了AspectJ的自动代理支持,即使用@EnableAspectJAutoProxy。如果项目中未包含此注解,注解定义的切面将不会生效。