CommonAnnotationBeanPostProcessor is used in Spring to process common annotations in JavaEE5 (mainly EJB-related annotations) and JAX-WS-related annotations in Java6. It can process annotations related to Bean life cycle events such as @PostConstruct and @PreDestroy. The core is to process
@Resource
annotations, as well as JAX-WS related annotations.
1. Trigger method
- After each bean is instantiated, the Spring container calls the
postProcessMergedBeanDefinition
method of the post-processor CommonAnnotationBeanPostProcessor to find out whether the bean has the @Resource annotation. - When Spring is instantiating each bean, it calls
populateBean
the attribute injection, that is, calls thepostProcessPropertyValues
method to find out whether the bean has the @Resource annotation.
2. Constructor
//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");
}
3. Injection
//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;
}
Continue to follow and see metadata.inject(bean, beanName, pvs)
how
//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);
}
}
}
The AutowiredAnnotationBeanPostProcessor
difference here is that the method called by AutowiredAnnotationBeanPostProcessor element.inject(target, beanName, pvs)
is implemented by itself, as shown in the figure:
The original method is CommonAnnotationBeanPostProcessor
called , as follows: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();
}
}
}
Here we focus on getResourceToInject(target, requestingBeanName)
the method. The implementation of this method is to specifically obtain the value in @Resource. We can see that in the CommonAnnotationBeanPostProcessor class, there is an implementation of this method:
//CommonAnnotationBeanPostProcessor.java
protected Object getResourceToInject(Object target, @Nullable String requestingBeanName) {
return (this.lazyLookup ? buildLazyResourceProxy(this,requestingBeanName) :
getResource(this, requestingBeanName));
}
lazyLookup
Is a member variable of the CommonAnnotationBeanPostProcessor internal class ResourceElement, indicating whether lazy loading, the default is false. Let's first look at the non-lazy loading process, namely 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 code:
//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;
}
The logic here is relatively simple:
- First determine whether @Resource is queried by name or type. If it is a type, call the dependency parser to find it from the Spring container according to the type (this is the same as the code of @Autowired: Spring annotation @Autowired source code analysis )
- If it is by name, the method of BeanFactory is called directly, and it
getBean()
is looked up from the Spring container according to BeanName - Finally, due to dependency injection, it is necessary to re-register the Bean's dependencies
总结
- The @Resource annotation can be injected either by name or by type.