溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

spring bean的自動注入及循環(huán)依賴問題怎么解決

發(fā)布時間:2023-03-23 16:00:55 來源:億速云 閱讀:189 作者:iii 欄目:開發(fā)技術

這篇文章主要介紹了spring bean的自動注入及循環(huán)依賴問題怎么解決的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇spring bean的自動注入及循環(huán)依賴問題怎么解決文章都會有所收獲,下面我們一起來看看吧。

一、spring中的各種注入方式

我們對Bean的注入,一般有下面幾種方式:

1)、通過@Autowired、@Resource作用在屬性上

2)、通過@Autowired、@Resource作用在方法上

3)、通過提供set方法+改變注入模型為自動注入

4)、通過BeanDefinition方式完成屬性注入

我們先說前三種方式:

我們用下面的測試類來檢驗:

1、測試注解作用在屬性上:

@Component
public class AnnotationAutowiredFiledBeanTest {
}

2、測試注解作用在方法上:

@Component
public class AnnotationAutowiredMethodBeanTest {
}

3、測試通過提供set方法+改變注入模型為自動注入

@Component
public class AutowiredInjectByTypeMethodBeanTest {
}

修改為注入模型類:

/**
 * 用來設置SpringBeanInfoTest類的屬性注入為自動注入模式
 *
 * */
@Component
public class UpdateBeanInfoBeanFactoryPostProcessor implements BeanFactoryPostProcessor{
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		AbstractBeanDefinition a = (AbstractBeanDefinition) beanFactory.getBeanDefinition("a");
		a.setAutowireMode(2);
		//a.getPropertyValues().add("beanDefinitionPropertyValuesBeanTest",new BeanDefinitionPropertyValuesBeanTest());
	}
}

4、各種方式的注入類:

@Component("a")
public class SpringBeanInfoTest {
 
	//@Autowired作用在屬性上進行注入
	@Autowired
	AnnotationAutowiredFiledBeanTest autowiredFiledBeanTest;
 
	//@Autowired作用在方法上進行注入
	@Autowired
	public void setAnnotationAutowiredMethodBeanTest(AnnotationAutowiredMethodBeanTest annotationAutowiredMethodBeanTest){
		System.out.println("AnnotationAutowiredMethodBeanTest=[{}]"+annotationAutowiredMethodBeanTest);
	}
 
	//使用自動注入(使用byType的模式)
	public void setAutowiredInjectByTypeMethodBeanTest(AutowiredInjectByTypeMethodBeanTest autowiredInjectByTypeMethodBeanTest){
		System.out.println("AutowiredInjectByTypeMethodBeanTest=[{}]"+autowiredInjectByTypeMethodBeanTest);
	}
 
 
 
 
	//用來打印@Autowired作用在屬性上進行注入是否成功
	public void printf(){
		System.out.println("autowiredFiledBeanTest=[{}]"+autowiredFiledBeanTest);
	}
 
}

5、啟動測試類:

配置類:

@Configuration
@ComponentScan("com.spring.demo.introspect")
public class App {
 
}

啟動類:

public class ApplicationTest {
 
 
@Test
	public void testSpringInject() throws NoSuchFieldException, IntrospectionException {
		AnnotationConfigApplicationContext context
				= new AnnotationConfigApplicationContext();
		context.register(App.class);
		context.refresh();
		context.getBean(SpringBeanInfoTest.class).printf();
    }
}

此時我們在UpdateBeanInfoBeanFactoryPostProcessor類中設置了SpringBeanInfoTest類的屬性注入為自動注入(2,默認為0)。我們運行下看看注入情況:

此時發(fā)現三種情況都能進行注入

spring bean的自動注入及循環(huán)依賴問題怎么解決

此時我們修改注入模型為默認的手動注入。

/**
 * 用來設置SpringBeanInfoTest類的屬性注入為自動注入模式
 *
 * */
@Component
public class UpdateBeanInfoBeanFactoryPostProcessor implements BeanFactoryPostProcessor{
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		AbstractBeanDefinition a = (AbstractBeanDefinition) beanFactory.getBeanDefinition("a");
		//a.setAutowireMode(2);
		//a.getPropertyValues().add("beanDefinitionPropertyValuesBeanTest",new BeanDefinitionPropertyValuesBeanTest());
	}
}

結果打印

spring bean的自動注入及循環(huán)依賴問題怎么解決

此時發(fā)現第三種方式無法注入了。

那么此時我們再來測試下第四種方式(通過BeanDefinition方式)

我們知道java內省機制最后都是講解析出來的屬性等轉換為一個BeanInfo對象,然后所有屬性等信息存在一個PropertyDescriptor數組中,而spring中在BeanDefinition中定義了一個MutablePropertyValues對象(propertyValues)中的一個List用來定義描述這個類的屬性等,那么我們要往SpringBeanInfoTest中注入一個屬性,此時就可以往這個List中存進我們要注入的對象即可。

(其實四種方式都是往propertyValues的List中添加屬性內容,最后會對這個list進行統(tǒng)一的處理。只是前三種通過不同方式獲取到屬性內容,然后放進list,而第四種則是直接add進行)

我們先編寫一個測試類(這里不用@Component):

public class BeanDefinitionPropertyValuesBeanTest {
}

此時在UpdateBeanInfoBeanFactoryPostProcessor 類中進行BeanDefinition方式的注入:

/**
 * 用來設置SpringBeanInfoTest類的屬性注入為自動注入模式
 *
 * */
@Component
public class UpdateBeanInfoBeanFactoryPostProcessor implements BeanFactoryPostProcessor{
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		AbstractBeanDefinition a = (AbstractBeanDefinition) beanFactory.getBeanDefinition("a");
		
		a.getPropertyValues().add("beanDefinitionPropertyValuesBeanTest",new BeanDefinitionPropertyValuesBeanTest());
	}
}

這里由于是手動的修改BeanDefinition對象,所以其注入模型并不會影響到這個是否生效。

然后在SpringBeanInfoTest中添加注入方法:

@Component("a")
public class SpringBeanInfoTest {
 
	//@Autowired作用在屬性上進行注入
	@Autowired
	AnnotationAutowiredFiledBeanTest autowiredFiledBeanTest;
 
	//@Autowired作用在方法上進行注入
	@Autowired
	public void setAnnotationAutowiredMethodBeanTest(AnnotationAutowiredMethodBeanTest annotationAutowiredMethodBeanTest){
		System.out.println("AnnotationAutowiredMethodBeanTest=[{}]"+annotationAutowiredMethodBeanTest);
	}
 
	//使用自動注入(使用byType的模式)
	public void setAutowiredInjectByTypeMethodBeanTest(AutowiredInjectByTypeMethodBeanTest autowiredInjectByTypeMethodBeanTest){
		System.out.println("AutowiredInjectByTypeMethodBeanTest=[{}]"+autowiredInjectByTypeMethodBeanTest);
	}
 
	//添加使用BeanDefinition方式進行屬性注入
	public void setBeanDefinitionPropertyValuesBeanTest(BeanDefinitionPropertyValuesBeanTest beanDefinitionPropertyValuesBeanTest){
		System.out.println("BeanDefinitionPropertyValuesBeanTest=[{}]"+beanDefinitionPropertyValuesBeanTest);
	}
	
 
	//用來打印@Autowired作用在屬性上進行注入是否成功
	public void printf(){
		System.out.println("autowiredFiledBeanTest=[{}]"+autowiredFiledBeanTest);
	}
 
}

我們可以來看看是否生效:

spring bean的自動注入及循環(huán)依賴問題怎么解決

可以看是可以進行注入的。

下面我們可以先簡單的對這四種情況做個總結,后續(xù)再進行源碼分析驗證猜想:

1)、在一個屬性上面加一個@Autowired注解

使用反射機制進行注入,可以看@Autowired源碼,偽代碼大概如下:

Class clazz = null;
Field autowiredFiledBeanTest = clazz.getDeclaredField("autowiredFiledBeanTest");
autowiredFiledBeanTest.setAccessible(true);
autowiredFiledBeanTest.set(this,getBean(AnnotationAutowiredFiledBeanTest.class));

2)、在一個方法上面加一個@Autowired注解

 2.1如果注入模型是1、2 (自動注入),那么spring底層采用的是java的自省機制發(fā)現setter方法然后調用執(zhí)行
* 也就是說方法上面的@Autowierd注解無用,直接走內省機制進行注入而不是通過解析@Autowierd進行注入

 2.2如果注入模型為0(默認值,手動注入) 那么則是和在屬性上面加注解差不多,底層查找所有加了@Autowired注解的方法,然后反射調用method.invoke()
3)、提供一個setter方法,繼而把該bean的注入模型改成1、2 自動注入

* 3.1  注入模型是自動注入 則是java的內省機制
偽代碼如下:

BeanInfo beanInfo = Introspector.getBeanInfo(SpringBeanInfoTest.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
 
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
	Method writeMethod = propertyDescriptor.getWriteMethod();
	writeMethod.invoke(this,getBean(parma))
}

4)、使用BeanDefinition方式進行注入

不和注入模型有相關聯,即所有情況都能生效

------------------------------------------源碼驗證

入口:refresh---》

finishBeanFactoryInitialization----》beanFactory.preInstantiateSingletons();---》
getBean---》doGetBean---》createBean-----》doCreateBean----》populateBean
我們進入populateBean方法看看:

//先從容器中獲取bean,有則直接返回進行注入
	//無則調用createBean創(chuàng)建需要進行注入的bean,放進單例池,最后再進行注入
	protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
		if (bw == null) {
			if (mbd.hasPropertyValues()) {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
			}
			else {
				// Skip property population phase for null instance.
				return;
			}
		}
 
		// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
		// state of the bean before properties are set. This can be used, for example,
		// to support styles of field injection.
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						return;
					}
				}
			}
		}
 
		//1、獲取到MutablePropertyValues對象,里面的List<PropertyValue> propertyValueList封裝著一些屬性的定義
		//這里現在只能獲取到手動使用BeanDefinition動態(tài)添加的屬性
		PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
 
		//獲取注入模型
		int resolvedAutowireMode = mbd.getResolvedAutowireMode();
		//2、注入模型為1或者2(自動注入),通過內省機制獲取所有符合的屬性(包括獲取到使用了@Autowired注解的set),并getbean放進propertyValueList中
		if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
			// Add property values based on autowire by name if applicable.
			//獲取到符合規(guī)則的屬性(setter)
			//然后獲取到該屬性的bean,并加入到MutablePropertyValues中的List中
			if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}
			// Add property values based on autowire by type if applicable.
			//獲取到符合規(guī)則的屬性(setter)
			// 然后獲取到該屬性的bean,并加入到MutablePropertyValues中的List中
			if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}
			//所有符合上面的屬性都會加到這里
			pvs = newPvs;
		}
 
		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
 
		//3、如果注入模型為0,手動注入,此時這里的propertyValueList只會存在我們手動使用BeanDefinition add進去的。
		//那么到這里為止所有set方法都沒被識別到(既不會在applyPropertyValues中執(zhí)行了)
		//下面的循環(huán)則是去解析@Autowired作用的屬性、方法(反射機制)
		//注意:如果該屬性已經存在propertyValueList,這里則不會對其進行解析(即自動注入模型下@Autowired作用在方法的被忽略執(zhí)行)
		PropertyDescriptor[] filteredPds = null;
		if (hasInstAwareBpps) {
			if (pvs == null) {
				pvs = mbd.getPropertyValues();
			}
 
			//獲取到所有BeanPostProcessor
			//如果是InstantiationAwareBeanPostProcessor,即處理@Autowired注解、@Resouce注解、@PostConstruct注解的BeanPostProcessor類型,則完成注入等操作
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				//完成@Autowired作用在屬性、方法上面的處理(使用反射)
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					//完成@Autowired作用在屬性、方法上面的處理
					PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
					if (pvsToUse == null) {
						if (filteredPds == null) {
							filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
						}
						pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
						if (pvsToUse == null) {
							return;
						}
					}
					pvs = pvsToUse;
				}
			}
		}
		if (needsDepCheck) {
			if (filteredPds == null) {
				filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
			}
			checkDependencies(beanName, mbd, filteredPds, pvs);
		}
 
		//4、處理propertyValueList中的所有還未執(zhí)行的屬性
		//遍歷屬性名、對象,內省機制調用invoke方法執(zhí)行set方法等
		if (pvs != null) {
			applyPropertyValues(beanName, mbd, bw, pvs);
		}
	}

關于“spring bean的自動注入及循環(huán)依賴問題怎么解決”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“spring bean的自動注入及循環(huán)依賴問題怎么解決”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI