1. 代理创建器
- 自动创建代理对象,将一个切面织入到多个目标对象中
- 三种自动代理创建器
- BeanNameAutoProxyCreator: 基于配置名规则
- DefaultAdvisorAutoProxyCreator: 基于 Advisor 匹配机制
- AbstractAdvisorAutoProxyCreator:
2. BeanNameAutoProxyCreator
2.1 剖析 BeanNameAutoProxyCreator
- BeanNameAutoProxyCreator 间接继承 BeanPostProcessor
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 自定义拦截器链
- beanNames 指定一组需要自动代理的Bean
- interceptorNames 指定一个或多个增强Bean
<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
- 扫描容器中的 Advisor, 并自动为匹配的目标 Bean 创建代理
网友评论