AOP - Advisor
-
定义通知
public class LoggingAdvice implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println("Method " + invocation.getMethod().getName() + " is being called"); return invocation.proceed(); // 继续执行目标方法 } }
-
定义切点
public class LoggingPointcut implements Pointcut { @Override public ClassFilter getClassFilter() { return ClassFilter.TRUE; // 适用于所有类 } @Override public MethodMatcher getMethodMatcher() { return new NameMatchMethodMatcher() { @Override public boolean matches(String methodName, Class<?> targetClass) { return methodName.startsWith("get"); // 适用于所有以 "get" 开头的方法 } }; } }
-
定义切面类
public class LoggingAdvisor extends DefaultPointcutAdvisor { public LoggingAdvisor() { super(new LoggingPointcut(), new LoggingAdvice()); } }
-
注册切面
@Configuration public class AopConfig { @Bean public LoggingAdvisor loggingAdvisor() { return new LoggingAdvisor(); } }