Spring AOP 组件 (Advice, Advisor,

2023-12-19  本文已影响0人  Tinyspot

1. Advice, Advisor 和 Advised

Advice 表示增强,有多种增强类型 (BeforAdvice, AfterReturningAdvice 等)

package org.aopalliance.aop;
public interface Advice {
}

Advisor 持有 Advice

public interface Advisor {
    Advice EMPTY_ADVICE = new Advice() {};

    Advice getAdvice();

    boolean isPerInstance();
}

Advised 是 AOP 代理工厂配置类接口,提供操作和管理 Advice 和 Advisor 的能力

public interface Advised extends TargetClassAware {
    // ...
    Advisor[] getAdvisors();
    void addAdvisor(Advisor advisor) throws AopConfigException;

    void addAdvice(Advice advice) throws AopConfigException;
}

2. Advice (增强)

@Configuration
public class BusinessInterceptorConfig {

    @Bean
    public Advice loginInterceptor() {
        return new LoginInterceptor();
    }
}
@Slf4j
public class LoginInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        log.info(this.getClass().getSimpleName() + "; " + invocation.getMethod().getName());
        return invocation.proceed();
    }
}

3. Advisor(通知器)

@Configuration
public class BusinessInterceptorConfig {
    @Bean
    public Advisor businessAdvisor() {
        MyInterceptor myInterceptor = new MyInterceptor();
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
        AnnotationMatchingPointcut pointcut = new AnnotationMatchingPointcut(null, InterceptAnno.class, true);
        advisor.setPointcut(pointcut);
        advisor.setAdvice(myInterceptor);
        return advisor;
    }
}

或者

@Configuration
public class MyInterceptorConfig {
    @Bean
    public Advice myInterceptor() {
        return new MyInterceptor();
    }

    @Bean
    public Advisor pointcutAdvisor() {
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
        // 设置 checkInherited = true
        // AnnotationMatchingPointcut pointcut = new AnnotationMatchingPointcut(null, InterceptAnno.class, true);
        AnnotationMatchingPointcut pointcut = new AnnotationMatchingPointcut(InterceptAnno.class, true);
        advisor.setPointcut(pointcut);
        advisor.setAdvice(myInterceptor());
        return advisor;
    }
}
上一篇下一篇

猜你喜欢

热点阅读