在Spring AOP中,可以使用注解来定义切面和切点。
<aop:aspectj-autoproxy />
@Aspect
注解标记:@Aspect public class LoggingAspect { // ... }
@Pointcut
注解标记:@Pointcut("execution(* com.example.service.*.*(..))") public void serviceMethods() {}
@Before
、@After
、@Around
等注解标记:@Before("serviceMethods()") public void beforeAdvice() { // 在目标方法执行前执行的逻辑 } @After("serviceMethods()") public void afterAdvice() { // 在目标方法执行后执行的逻辑 } @Around("serviceMethods()") public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable { // 在目标方法执行前后执行的逻辑 Object result = joinPoint.proceed(); // 在目标方法执行后执行的逻辑 return result; }
@Service public class UserService { @Loggable public void addUser(User user) { // ... } }
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Loggable { }
以上就是使用注解的方式来使用Spring AOP的基本步骤。在实际使用中,可以根据具体需求选择不同的注解和切点表达式,来定义切面和切点。