AOP - Advisor

CyrusHuang發表於2024-10-20
  1. 定義通知

    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(); // 繼續執行目標方法
        }
    }
    
  2. 定義切點

    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" 開頭的方法
                }
            };
        }
    }
    
  3. 定義切面類

    public class LoggingAdvisor extends DefaultPointcutAdvisor {
        public LoggingAdvisor() {
            super(new LoggingPointcut(), new LoggingAdvice());
        }
    }
    
  4. 註冊切面

    @Configuration
    public class AopConfig {
        @Bean
        public LoggingAdvisor loggingAdvisor() {
            return new LoggingAdvisor();
        }
    }
    

相關文章