spring.io

Spring AOP 自动创建代理

2022-11-16  本文已影响0人  Tinyspot

1. 代理创建器

2. BeanNameAutoProxyCreator

2.1 剖析 BeanNameAutoProxyCreator

image.png
public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator {
    // e.g. "myBean,tx*"
    public void setBeanNames(String... beanNames) {
        Assert.notEmpty(beanNames, "'beanNames' must not be empty");
        this.beanNames = new ArrayList<>(beanNames.length);
        for (String mappedName : beanNames) {
            this.beanNames.add(StringUtils.trimWhitespace(mappedName));
        }
    }
}

2.2 自定义拦截器链

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
import org.aopalliance.aop.Advice;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Aspect
@Configuration
public class BusinessInterceptorConfig {

    @Bean
    public BeanNameAutoProxyCreator beanNameAutoProxyCreator() {
        BeanNameAutoProxyCreator creator = new BeanNameAutoProxyCreator();
        // creator.setBeanNames("greetService", "userService");
        creator.setBeanNames("*Impl");
        // 设置拦截链,有顺序
        creator.setInterceptorNames("sessionIntercept", "loginIntercept");
        // creator.setProxyTargetClass(true);
        return creator;
    }

    // 创建Advice
    @Bean
    public Advice sessionIntercept() {
        return new SessionIntercept();
    }

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

@Slf4j
public class LoginIntercept implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        log.info(this.getClass() + "; " + invocation.getMethod().getName() + "; do something...");
        return invocation.proceed();
    }
}

3. DefaultAdvisorAutoProxyCreator

上一篇下一篇

猜你喜欢

热点阅读