文章目錄
Spring Aop的核心
就是生成動態代理
和動態代理織入
,本篇主要講Spring Aop生成動態代理
,Spring Aop動態代理織入
在Spring Aop動態代理織入博文中
Spring Aop生成動態代理出現在創建bean時,主要使用了工廠模式
、動態代理模式
、享元模式
等設計模式。Aop首先調用AbstractBeanFactory#doGetBean()方法創建來bean
doGetBean(name, null, null, false)
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType, @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
// 這一大段代碼省略
......
// 真正創建bean
return createBean(beanName, mbd, args);
// 這一大段代碼省略
......
}
createBean(beanName, mbd, args)
/**
* Spring Aop功能是使用Spring提供的擴展點BeanPostProcessor後置處理器來實現對切面信息的讀取和緩存
*/
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
// 這一大段代碼省略
......
// 主要是來執行實現了InstantiationAwareBeanPostProcessor接口的BeanPostProcesser
// AOP核心方法,用來處理使用@Aspect註解標識的切面bean,讀取切面bean中的信息,添加到advisorsCache緩存中,以便後面生成動態代理
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
// 實例化bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
// 這一大段代碼省略
......
}
切面信息的讀取和緩存
resolveBeforeInstantiation(beanName, mbdToUse)
/**
* AOP核心方法,用來處理使用@Aspect註解標識的切面bean,讀取切面bean中的信息,添加到advisorsCache緩存中,以便後面生成動態代理
*/
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
// 檢測是否被解析過
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// hasInstantiationAwareBeanPostProcessors()是來判斷容器中是否有InstantiationAwareBeanPostProcessor的實現bean
// AOP切面後置處理器AspectJAwareAdvisorAutoProxyCreator就實現了InstantiationAwareBeanPostProcessor接口
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = determineTargetType(beanName, mbd); // 獲取bean的目標類型
if (targetType != null) {
// 執行實現了InstantiationAwareBeanPostProcessor接口的BeanPostProcessor中的前置處理方法postProcessBeforeInstantiation方法
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
// 執行實現了InstantiationAwareBeanPostProcessor接口的BeanPostProcessor中的後置處理方法postProcessAfterInitialization方法
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
applyBeanPostProcessorsBeforeInstantiation(targetType, beanName)
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 調用實現InstantiationAwareBeanPostProcessor接口的方法
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
ibp.postProcessBeforeInstantiation(beanClass, beanName)
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
Object cacheKey = getCacheKey(beanClass, beanName);
if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
if (this.advisedBeans.containsKey(cacheKey)) {
return null;
}
// shouldSkip(beanClass, beanName)中
if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return null;
}
}
TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
if (targetSource != null) {
if (StringUtils.hasLength(beanName)) {
this.targetSourcedBeans.add(beanName);
}
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
return null;
}
shouldSkip(beanClass, beanName)
protected boolean shouldSkip(Class<?> beanClass, String beanName) {
// 找到我們的切面
List<Advisor> candidateAdvisors = findCandidateAdvisors();
for (Advisor advisor : candidateAdvisors) {
if (advisor instanceof AspectJPointcutAdvisor &&
((AspectJPointcutAdvisor) advisor).getAspectName().equals(beanName)) {
return true;
}
}
return super.shouldSkip(beanClass, beanName);
}
findCandidateAdvisors()
protected List<Advisor> findCandidateAdvisors() {
// 第一次調用AbstractAutoProxyCreator實現類AnnotationAwareAspectJAutoProxyCreator中實現的方法postProcessBeforeInstantiation時進行初始化切面信息,並添加到advisorsCache緩存中
// 這是事務的切面
List<Advisor> advisors = super.findCandidateAdvisors();
// 這是AspectJ的切面
if (this.aspectJAdvisorsBuilder != null) {
advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
}
return advisors;
}
this.aspectJAdvisorsBuilder.buildAspectJAdvisors()
public List<Advisor> buildAspectJAdvisors() {
List<String> aspectNames = this.aspectBeanNames;
// aspectNames用來存儲切面bean的beanName
if (aspectNames == null) {
synchronized (this) {
aspectNames = this.aspectBeanNames;
if (aspectNames == null) {
List<Advisor> advisors = new ArrayList<>();
aspectNames = new ArrayList<>();
// 獲取BeanDefinitionMap中所有類型爲Object的的beanName
String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.beanFactory, Object.class, true, false);
// 遍歷所有的bean
for (String beanName : beanNames) {
if (!isEligibleBean(beanName)) {
continue;
}
Class<?> beanType = this.beanFactory.getType(beanName);
if (beanType == null) {
continue;
}
// 只對bean類型爲Aspect的進行處理
if (this.advisorFactory.isAspect(beanType)) {
aspectNames.add(beanName);
// AspectMetadata對象是用來包裝Aspect切面類的信息
AspectMetadata amd = new AspectMetadata(beanType, beanName);
if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
// 將切面實例封裝爲切面實例工廠
MetadataAwareAspectInstanceFactory factory =
new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
// 根據實例工廠獲取切面中的顧問Advisor對象
List<Advisor> classAdvisors = this.advisorFactory.getAdvisors(factory);
// 判斷bean是否是單例的,如果是單例的,將切面bean的切面信息放入advisorsCache切面緩存中,方面後面後置處理器進行生成動態代理對象
if (this.beanFactory.isSingleton(beanName)) {
this.advisorsCache.put(beanName, classAdvisors);
}
else {
this.aspectFactoryCache.put(beanName, factory);
}
advisors.addAll(classAdvisors);
}
else {
// Per target or per this.
if (this.beanFactory.isSingleton(beanName)) {
throw new IllegalArgumentException("Bean with name '" + beanName + "' is a singleton, but aspect instantiation model is not singleton");
}
MetadataAwareAspectInstanceFactory factory =
new PrototypeAspectInstanceFactory(this.beanFactory, beanName);
this.aspectFactoryCache.put(beanName, factory);
advisors.addAll(this.advisorFactory.getAdvisors(factory));
}
}
}
this.aspectBeanNames = aspectNames;
return advisors;
}
}
}
// 這一大段代碼省略
......
return advisors;
}
生成動態代理對象
doCreateBean(beanName, mbdToUse, args)
/**
* 實例化bean對象
*/
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// 這一大段代碼省略
......
// 初始化bean實例
exposedObject = initializeBean(beanName, exposedObject, mbd);
// 這一大段代碼省略
......
return exposedObject;
}
initializeBean(beanName, exposedObject, mbd)
/**
* 初始化bean實例
*/
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
// 這一大段代碼省略
......
// 在bean初始化之後調用BeanPostProcessor後置處理器中的postProcessAfterInitialization方法
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
return wrappedBean;
}
applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName)
/**
* BeanPostProcessor後置處理器中的postProcessAfterInitialization實現方法
*/
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
// 當processor的實現類是AbstractAutoProxyCreator時將會調用AbstractAutoProxyCreator對postProcessAfterInitialization方法的實現
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
processor.postProcessAfterInitialization(result, beanName)
/**
* BeanPostProcessor接口的實現抽象類AbstractAutoProxyCreator對postProcessAfterInitialization方法的實現
*/
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) throws BeansException {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
// 生成動態代理對象
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
wrapIfNecessary(bean, beanName, cacheKey)
/**
* 生成動態代理對象
*/
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
return bean;
}
if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
return bean;
}
// isInfrastructureClass(bean.getClass()):判斷這個bean是不是有沒有實現Advice、PuintCut、Advisor、AopInfrastructureBean接口
// shouldSkip(bean.getClass(), beanName):應不應該跳過
if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
// 獲取切面和切面方法
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
// 真正的創建代理對象
Object proxy = createProxy(
bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean))
/**
* 真正的創建動態代理對象
*/
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()) {
if (shouldProxyTargetClass(beanClass, beanName)) {
proxyFactory.setProxyTargetClass(true);
}
else {
evaluateProxyInterfaces(beanClass, proxyFactory);
}
}
// 獲取Advisor顧問對象
Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
proxyFactory.addAdvisors(advisors);
proxyFactory.setTargetSource(targetSource);
customizeProxyFactory(proxyFactory);
proxyFactory.setFrozen(this.freezeProxy);
if (advisorsPreFiltered()) {
proxyFactory.setPreFiltered(true);
}
// 從動態代理工廠中獲取代理對象
return proxyFactory.getProxy(getProxyClassLoader());
}
proxyFactory.getProxy(getProxyClassLoader())
/**
* 從動態代理工廠中獲取代理對象
*/
public Object getProxy(@Nullable ClassLoader classLoader) {
return createAopProxy().getProxy(classLoader);
}
createAopProxy()
/**
* 創建Aop動態代理
*/
protected final synchronized AopProxy createAopProxy() {
if (!this.active) {
activate();
}
return getAopProxyFactory().createAopProxy(this);
}
getAopProxyFactory().createAopProxy(this)
/**
* 創建Aop動態代理的真正實現
*/
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
// config.isProxyTargetClass()默認值爲false
// hasNoUserSuppliedProxyInterfaces(config)判斷該bean是否是接口,如果是接口,直接使用JDK動態代理
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
Class<?> targetClass = config.getTargetClass();
if (targetClass == null) {
throw new AopConfigException("TargetSource cannot determine target class: " +
"Either an interface or a target is required for proxy creation.");
}
// ProxyTargetClass爲true時使用Cglib動態代理
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
// 否則爲JDK動態代理
return new ObjenesisCglibAopProxy(config);
}
// 當ProxyTargetClass爲false 或者 該bean時接口時 使用JDK動態代理
else {
return new JdkDynamicAopProxy(config);
}
}
hasNoUserSuppliedProxyInterfaces(config)
/**
* 判斷該bean是否是接口
*/
private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
Class<?>[] ifcs = config.getProxiedInterfaces();
return (ifcs.length == 0 || (ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0])));
}
createAopProxy().getProxy(classLoader)
/**
* 從創建的動態代理中生成代理對象(這裏是使用JDK動態的)
*/
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isDebugEnabled()) {
logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
}
Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
// 調用Proxy.newProxyInstance()方法生成JDK動態代理對象並返回
return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}
存儲動態代理對象
在經過Object beanInstance = doCreateBean(beanName, mbdToUse, args);
獲取了bean實例,將其返回給方法調用的createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
方法,然後再返回給調用的getSingleton(String beanName, ObjectFactory<?> singletonFactory)
方法
getSingleton(String beanName, ObjectFactory<?> singletonFactory)
/**
* 獲取單例的bean實例,如果bean實例不存在的話就創建
* 從addSingleton(beanName, singletonObject)可以看出,最後生成的代理對象和普通bean一樣被添加到singletonObjects單例池(一級緩存)中
*/
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
// 這一大塊代碼省略
......
// 調用ObjectFactory接口實現類中的getObject()方法,這裏是使用lambad表達式來進行重新getObject()方法的
singletonObject = singletonFactory.getObject();
// 這一大塊代碼省略
......
// 將singletonObject添加到singletonObjects一級緩存中,同時將二級、三級緩存中的bean刪除
addSingleton(beanName, singletonObject);
return singletonObject;
}
}