天天看點

Spring注解@Resource源碼分析

CommonAnnotationBeanPostProcessor是Spring中用于處理JavaEE5中常用注解(主要是EJB相關的注解)和Java6中關于JAX-WS相關的注解,可以處理@PostConstruct、@PreDestroy等Bean生命周期相關事件的注解,該後置處理最核心的是處理

@Resource

注解,同時還可以處理JAX-WS相關的注解。

一、觸發方式

  • Spring容器在每個Bean執行個體化之後,調用後置處理器CommonAnnotationBeanPostProcessor的

    postProcessMergedBeanDefinition

    方法,查找該Bean是否有@Resource注解。
  • Spring在每個Bean執行個體化的時候,調用

    populateBean

    進行屬性注入的時候,即調用

    postProcessPropertyValues

    方法,查找該Bean是否有@Resource注解。

二、構造函數

//CommonAnnotationBeanPostProcessor.java

//構造方法
public CommonAnnotationBeanPostProcessor() {
	setOrder(Ordered.LOWEST_PRECEDENCE - 3);
	//設定初始的注解類型為@PostConstruct
	setInitAnnotationType(PostConstruct.class);
	//設定銷毀的注解為@ PreDestroy
	setDestroyAnnotationType(PreDestroy.class);
	//當使用@Resource注解時,忽略JAX-WS的資源類型
	ignoreResourceType("javax.xml.ws.WebServiceContext");
	}           

複制

三、注入

//CommonAnnotationBeanPostProcessor.java

public PropertyValues postProcessPropertyValues(
		PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {

	//擷取@Resource注解中配置的屬性值中繼資料
	InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass(), pvs);
	try {
		//注入屬性值,與AutowiredAnnotationBeanPostProcessor中處理相同
		metadata.inject(bean, beanName, pvs);
	}
	catch (Throwable ex) {
		throw new BeanCreationException(beanName, "Injection of resource dependencies failed", ex);
	}
	return pvs;
	}           

複制

繼續追蹤,看

metadata.inject(bean, beanName, pvs)

方法

//InjectionMetadata.java

public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
	Collection<InjectedElement> checkedElements = this.checkedElements;
	//要注入的字段集合
	Collection<InjectedElement> elementsToIterate =
			(checkedElements != null ? checkedElements : this.injectedElements);
	if (!elementsToIterate.isEmpty()) {
		boolean debug = logger.isDebugEnabled();
		//周遊 注入
		for (InjectedElement element : elementsToIterate) {
			if (debug) {
				logger.debug("Processing injected element of bean '" + beanName + "': " + element);
			}
			element.inject(target, beanName, pvs);
		}
	}
	}           

複制

這裡和

AutowiredAnnotationBeanPostProcessor

不同的是,AutowiredAnnotationBeanPostProcessor調用的

element.inject(target, beanName, pvs)

方法是自己實作的,如圖:

Spring注解@Resource源碼分析

CommonAnnotationBeanPostProcessor

調用的

element.inject(target, beanName, pvs)

是原始方法,如下:

//InjectionMetadata.java

protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs)
		throws Throwable {

	if (this.isField) {
		Field field = (Field) this.member;
		//強吻通路
		ReflectionUtils.makeAccessible(field);
		//給字段指派,即屬性注入
		field.set(target, getResourceToInject(target, requestingBeanName));
	}
	else {
		if (checkPropertySkipping(pvs)) {
			return;
		}
		try {
		        //方法注入
			Method method = (Method) this.member;
			ReflectionUtils.makeAccessible(method);
			method.invoke(target, getResourceToInject(target, requestingBeanName));
		}
		catch (InvocationTargetException ex) {
			throw ex.getTargetException();
		}
	}
	}           

複制

這裡重點看

getResourceToInject(target, requestingBeanName)

方法,該方法的實作是具體擷取@Resource中的值的。 我們可以看到在CommonAnnotationBeanPostProcessor類中,對該方法有實作:

//CommonAnnotationBeanPostProcessor.java

protected Object getResourceToInject(Object target, @Nullable String requestingBeanName) {
	return (this.lazyLookup ? buildLazyResourceProxy(this,requestingBeanName) :
		getResource(this, requestingBeanName));
	}           

複制

lazyLookup

是CommonAnnotationBeanPostProcessor内部類ResourceElement的一個成員變量,表示是否懶加載,預設是false。 我們先來看下非懶加載的流程,即

getResource(this, requestingBeanName)

:

//CommonAnnotationBeanPostProcessor.java

//根據給定名稱或者類型擷取資源對象
	protected Object getResource(LookupElement element, @Nullable String requestingBeanName) throws BeansException {
	//如果注解對象元素的mappedName屬性不為空
	if (StringUtils.hasLength(element.mappedName)) {
		//根據JNDI名稱和類型去Spring的JNDI容器中擷取Bean
		return this.jndiFactory.getBean(element.mappedName, element.lookupType);
	}
	//如果該後置處理器的alwaysUseJndiLookup屬性值為true
	if (this.alwaysUseJndiLookup) {
		//從Spring的JNDI容器中查找指定JDNI名稱和類型的Bean
		return this.jndiFactory.getBean(element.name, element.lookupType);
	}
	if (this.resourceFactory == null) {
		throw new NoSuchBeanDefinitionException(element.lookupType,
				"No resource factory configured - specify the 'resourceFactory' property");
	}
	//使用autowiring自動依賴注入裝配,通過給定的名稱和類型從資源容器擷取Bean對象
	//一般情況下,都是走這一步
	return autowireResource(this.resourceFactory, element, requestingBeanName);
	}           

複制

autowireResource代碼:

//CommonAnnotationBeanPostProcessor.java

protected Object autowireResource(BeanFactory factory, LookupElement element, @Nullable String requestingBeanName)
		throws BeansException {

	Object resource;
	Set<String> autowiredBeanNames;
	String name = element.name;

	if (this.fallbackToDefaultTypeMatch && element.isDefaultName &&
			factory instanceof AutowireCapableBeanFactory && !factory.containsBean(name)) {
		autowiredBeanNames = new LinkedHashSet<>();
		//根據類型從Spring容器中查找資源
		//調用依賴解析器,跟@Autowired是同樣的代碼
		resource = ((AutowireCapableBeanFactory) factory).resolveDependency(
				element.getDependencyDescriptor(), requestingBeanName, autowiredBeanNames, null);
		if (resource == null) {
			throw new NoSuchBeanDefinitionException(element.getLookupType(), "No resolvable resource object");
		}
	}
	//根據名稱從Spring容器中查找資源
	else {
		resource = factory.getBean(name, element.lookupType);
		autowiredBeanNames = Collections.singleton(name);
	}

	//注冊Bean的依賴關系
	if (factory instanceof ConfigurableBeanFactory) {
		ConfigurableBeanFactory beanFactory = (ConfigurableBeanFactory) factory;
		for (String autowiredBeanName : autowiredBeanNames) {
			if (requestingBeanName != null && beanFactory.containsBean(autowiredBeanName)) {
				beanFactory.registerDependentBean(autowiredBeanName, requestingBeanName);
			}
		}
	}

	return resource;
	}           

複制

這裡的邏輯比較簡單:

  • 首先判斷@Resource是按名稱來查詢還是類型,如果是類型,則調用依賴解析器根據類型從Spring容器中查找
  • 如果是按名稱,則直接調用BeanFactory的

    getBean()

    方法,根據BeanName從Spring容器中查找
  • 最後由于發生了依賴注入,需要從新注冊Bean的依賴關系
總結
  • @Resource注解既可以按照名稱來注入,也可以按類型來注入。