spring aop原理
自动配置类
AopAutoConfiguration
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnProperty(
prefix = "spring.aop",
name = {"auto"},
havingValue = "true",
matchIfMissing = true
) //是否自动使用aop,默认自动使用
public class AopAutoConfiguration {
public AopAutoConfiguration() {
}
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnMissingClass({"org.aspectj.weaver.Advice"})
@ConditionalOnProperty(
prefix = "spring.aop",
name = {"proxy-target-class"},
havingValue = "true",
matchIfMissing = true
) //不存在类org.aspectj.weaver.Advice时,使用ClassProxyingConfiguration代理
//springboot类路径中存在org.aspectj.weaver.Advice类,不使用该代理配置
static class ClassProxyingConfiguration {
ClassProxyingConfiguration() {
}
@Bean
static BeanFactoryPostProcessor forceAutoProxyCreatorToUseClassProxying() {
return (beanFactory) -> {
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry)beanFactory;
AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
}
};
}
}
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnClass({Advice.class}) //存在类Aadvce时,使用AspectJAutoProxyingConfiguration代理配置
//springboot类路径中存在Advice类,使用该配置类
static class AspectJAutoProxyingConfiguration {
AspectJAutoProxyingConfiguration() {
}
@Configuration(
proxyBeanMethods = false
)
@EnableAspectJAutoProxy(
proxyTargetClass = true
)
@ConditionalOnProperty(
prefix = "spring.aop",
name = {"proxy-target-class"},
havingValue = "true",
matchIfMissing = true
) //默认使用cglib动态代理
static class CglibAutoProxyConfiguration {
CglibAutoProxyConfiguration() {
}
}
@Configuration(
proxyBeanMethods = false
)
@EnableAspectJAutoProxy(
proxyTargetClass = false
)
@ConditionalOnProperty(
prefix = "spring.aop",
name = {"proxy-target-class"},
havingValue = "false"
) //当spring.aop.proxy-target-class=false时,使用jdk动态代理
static class JdkDynamicAutoProxyConfiguration { //jdk动态代理
JdkDynamicAutoProxyConfiguration() {
}
}
}
}
配置元数据
# additional-spring-configuration-metadata.json(aop部分)
{
"groups": [],
"properties": [
{
"name": "spring.aop.auto",
"type": "java.lang.Boolean",
"description": "Add @EnableAspectJAutoProxy.",
"defaultValue": true
}, #相当于添加注解@EnableAspectJAutoProxy
{
"name": "spring.aop.proxy-target-class",
"type": "java.lang.Boolean",
"description": "Whether subclass-based (CGLIB) proxies are to be created (true), as opposed to standard Java interface-based proxies (false).",
"defaultValue": true
} #springboot 2.x默认强制使用cglib代理
]
}
相关注解
EnableAspectJAutoProxy
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({AspectJAutoProxyRegistrar.class}) //导入类AspectJAutoProxyRegistrar
public @interface EnableAspectJAutoProxy {
boolean proxyTargetClass() default false;
boolean exposeProxy() default false; //可解决对象自调用失效(切面、事务等不会应用)
//如类ClassA,fun()内部调用fun2(),使用this.fun2(),此时不会使用代理
//可将exposeProxy设置为true,并修改调用处代码为:((ClassA)AopContext.currentProxy()).fun2()
}
AspectJAutoProxyRegistrar:注册AnnotationAwareAspectJAutoProxyCreator类,并设置属性
class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
AspectJAutoProxyRegistrar() {
}
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
//注册AnnotationAwareAspectJAutoProxyCreator类,该类负责创建aop代理
AnnotationAttributes enableAspectJAutoProxy = AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
if (enableAspectJAutoProxy != null) {
if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
} //如果proxyTargetClass为true,强制使用cglib代理
if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
} //如果exposeProxy,强制暴露代理对象
}
}
}
AopConfigUtils
public abstract class AopConfigUtils {
public static final String AUTO_PROXY_CREATOR_BEAN_NAME = "org.springframework.aop.config.internalAutoProxyCreator";
//AspectJAwareAdvisorAutoProxyCreator实例对象名称
private static final List<Class<?>> APC_PRIORITY_LIST = new ArrayList(3);
public AopConfigUtils() {
}
@Nullable
public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
return registerAutoProxyCreatorIfNecessary(registry, (Object)null);
}
@Nullable
public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, @Nullable Object source) {
return registerOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class, registry, source);
}
@Nullable
public static BeanDefinition registerAspectJAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
return registerAspectJAutoProxyCreatorIfNecessary(registry, (Object)null);
}
@Nullable
public static BeanDefinition registerAspectJAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, @Nullable Object source) {
return registerOrEscalateApcAsRequired(AspectJAwareAdvisorAutoProxyCreator.class, registry, source);
}
@Nullable
public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
return registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry, (Object)null);
} //注册AnnotationAwareAspectJAutoProxyCreator类信息
@Nullable
public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, @Nullable Object source) {
return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
}
public static void forceAutoProxyCreatorToUseClassProxying(BeanDefinitionRegistry registry) {
//强制使用cglib代理
if (registry.containsBeanDefinition("org.springframework.aop.config.internalAutoProxyCreator")) {
BeanDefinition definition = registry.getBeanDefinition("org.springframework.aop.config.internalAutoProxyCreator");
definition.getPropertyValues().add("proxyTargetClass", Boolean.TRUE);
} //将proxyTargetClass设为true
}
public static void forceAutoProxyCreatorToExposeProxy(BeanDefinitionRegistry registry) {
//强制将当前对象暴露为代理对象
if (registry.containsBeanDefinition("org.springframework.aop.config.internalAutoProxyCreator")) {
BeanDefinition definition = registry.getBeanDefinition("org.springframework.aop.config.internalAutoProxyCreator");
definition.getPropertyValues().add("exposeProxy", Boolean.TRUE);
} //将exposeProxy设为true
}
@Nullable
private static BeanDefinition registerOrEscalateApcAsRequired(Class<?> cls, BeanDefinitionRegistry registry, @Nullable Object source) {
//注册或者更新类信息
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
if (registry.containsBeanDefinition("org.springframework.aop.config.internalAutoProxyCreator")) {
//根据优先级更新类信息
BeanDefinition apcDefinition = registry.getBeanDefinition("org.springframework.aop.config.internalAutoProxyCreator");
//根据名称获取注册信息
if (!cls.getName().equals(apcDefinition.getBeanClassName())) {
//如果class信息不一样,根据优先级判断是否需要更新
int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());
//原注册信息优先级
int requiredPriority = findPriorityForClass(cls); //当前需注册的class的优先级
if (currentPriority < requiredPriority) {
apcDefinition.setBeanClassName(cls.getName());
} //原注册信息优先级小于当前需注册信息优先级,将注册信息更新为当前信息
}
return null;
} else {
RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
beanDefinition.setSource(source);
beanDefinition.getPropertyValues().add("order", -2147483648);
beanDefinition.setRole(2);
registry.registerBeanDefinition("org.springframework.aop.config.internalAutoProxyCreator", beanDefinition);
//注册bean信息
return beanDefinition;
}
}
private static int findPriorityForClass(Class<?> clazz) {
return APC_PRIORITY_LIST.indexOf(clazz);
}
private static int findPriorityForClass(@Nullable String className) {
for(int i = 0; i < APC_PRIORITY_LIST.size(); ++i) {
Class<?> clazz = (Class)APC_PRIORITY_LIST.get(i);
if (clazz.getName().equals(className)) {
return i;
}
}
throw new IllegalArgumentException("Class name [" + className + "] is not a known auto-proxy creator class");
}
static {
APC_PRIORITY_LIST.add(InfrastructureAdvisorAutoProxyCreator.class);
APC_PRIORITY_LIST.add(AspectJAwareAdvisorAutoProxyCreator.class);
APC_PRIORITY_LIST.add(AnnotationAwareAspectJAutoProxyCreator.class);
}
}
创建代理
AnnotationAwareAspectJAutoProxyCreator父类继承关系
继承了SmartInstantiationAwareBeanPostProcessor,
会在实例化前调用postProcessBeforeInstantiation方法,
初始化后调用postProcessAfterInitialization方法
AbstractAutoProxyCreator
public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
//实例化前调用该方法,创建代理对象
Object cacheKey = this.getCacheKey(beanClass, beanName);
//获取beanClass缓存的key
if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
if (this.advisedBeans.containsKey(cacheKey)) {
return null;
}
if (this.isInfrastructureClass(beanClass) || this.shouldSkip(beanClass, beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return null;
}
}
TargetSource targetSource = this.getCustomTargetSource(beanClass, beanName);
//获取当前bean的targetSource对象
if (targetSource != null) { //如果不为空,并且有对应的增强器,则创建代理对象
if (StringUtils.hasLength(beanName)) {
this.targetSourcedBeans.add(beanName);
}
Object[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
Object proxy = this.createProxy(beanClass, beanName, specificInterceptors, targetSource);
//创建代理对象
this.proxyTypes.put(cacheKey, proxy.getClass()); //缓存代理的类
return proxy; //返回代理对象
} else {
return null;
}
}
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
//初始化后调用该方法,创建相应代理对象
if (bean != null) {
Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
//如果对象没有提前暴露,创建代理对象
return this.wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean; //如果对象提前暴露了,不可创建代理对象,直接返回原对象
}
protected Object getCacheKey(Class<?> beanClass, @Nullable String beanName) {
if (StringUtils.hasLength(beanName)) { //beanName不为空的处理
return FactoryBean.class.isAssignableFrom(beanClass) ? "&" + beanName : beanName;
} else { //beanName为空,直接返回beanClass
return beanClass;
}
}
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
//如果已经处理过(targetSource),实例化前创建了代理对象,直接返回bean
return bean;
} else if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
return bean; //如果对象不需要增强,直接返回bean
} else if (!this.isInfrastructureClass(bean.getClass()) && !this.shouldSkip(bean.getClass(), beanName)) {
//如果对象时基础设施类、或者是originalInstance,不创建代理对象
//如果不是,则可创建代理对象
Object[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, (TargetSource)null);
//获取通知增强器
if (specificInterceptors != DO_NOT_PROXY) { //如果增强器不为空,则创建代理对象
this.advisedBeans.put(cacheKey, Boolean.TRUE);
Object proxy = this.createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
//创建代理对象
this.proxyTypes.put(cacheKey, proxy.getClass()); //缓存创建的代理对象
return proxy;
} else {
this.advisedBeans.put(cacheKey, Boolean.FALSE); //标记该对象不创建代理
return bean;
}
} else {
this.advisedBeans.put(cacheKey, Boolean.FALSE); //标记该对象不创建代理
return bean;
}
}
protected boolean shouldSkip(Class<?> beanClass, String beanName) {
return AutoProxyUtils.isOriginalInstance(beanName, beanClass);
}
protected Object createProxy(Class<?> beanClass, @Nullable String beanName, @Nullable Object[] specificInterceptors, TargetSource targetSource) {
//创建代理对象
if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory)this.beanFactory, beanName, beanClass);
}
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.copyFrom(this);
if (proxyFactory.isProxyTargetClass()) { //根据proxyTargetClass属性,设置代理接口(如果有接口)
if (Proxy.isProxyClass(beanClass)) { //beanClass是否是代理类
Class[] var6 = beanClass.getInterfaces(); //获取对象接口
int var7 = var6.length;
for(int var8 = 0; var8 < var7; ++var8) {
Class<?> ifc = var6[var8];
proxyFactory.addInterface(ifc); //依次遍历添加接口
}
}
} else if (this.shouldProxyTargetClass(beanClass, beanName)) {
proxyFactory.setProxyTargetClass(true); //cglib处理
} else { //jdk处理
this.evaluateProxyInterfaces(beanClass, proxyFactory);
}
Advisor[] advisors = this.buildAdvisors(beanName, specificInterceptors);
//构建增强器
proxyFactory.addAdvisors(advisors); //添加增强器
proxyFactory.setTargetSource(targetSource); //设置被代理的对象
this.customizeProxyFactory(proxyFactory); //自定义代理工厂
proxyFactory.setFrozen(this.freezeProxy); //配置工厂后,是否可以修改通知,默认false
if (this.advisorsPreFiltered()) {
proxyFactory.setPreFiltered(true);
}
ClassLoader classLoader = this.getProxyClassLoader();
if (classLoader instanceof SmartClassLoader && classLoader != beanClass.getClassLoader()) {
classLoader = ((SmartClassLoader)classLoader).getOriginalClassLoader();
}
return proxyFactory.getProxy(classLoader); //返回创建的代理对象
}
protected Advisor[] buildAdvisors(@Nullable String beanName, @Nullable Object[] specificInterceptors) {
//构建增强器
Advisor[] commonInterceptors = this.resolveInterceptorNames();
List<Object> allInterceptors = new ArrayList();
if (specificInterceptors != null) {
if (specificInterceptors.length > 0) {
allInterceptors.addAll(Arrays.asList(specificInterceptors));
}
if (commonInterceptors.length > 0) {
if (this.applyCommonInterceptorsFirst) {
allInterceptors.addAll(0, Arrays.asList(commonInterceptors));
} else {
allInterceptors.addAll(Arrays.asList(commonInterceptors));
}
}
}
int i;
if (this.logger.isTraceEnabled()) {
int nrOfCommonInterceptors = commonInterceptors.length;
i = specificInterceptors != null ? specificInterceptors.length : 0;
this.logger.trace("Creating implicit proxy for bean '" + beanName + "' with " + nrOfCommonInterceptors + " common interceptors and " + i + " specific interceptors");
}
Advisor[] advisors = new Advisor[allInterceptors.size()];
for(i = 0; i < allInterceptors.size(); ++i) {
advisors[i] = this.advisorAdapterRegistry.wrap(allInterceptors.get(i));
}
return advisors;
}