之前分析spring的依賴注入時,主要分析的是xml配置方式。但是在實際項目中,我們其實用的更多的是注解方式。這一篇博客會分析下spring是如何處理這種注解注入的。(主要分析最常使用的@Autowired 和 @Resource注解)
注解注入的開啟 annotation-config
SpringBoot方式暫且不管,正常來說我們要想啟用注解注入都需要有這樣一個配置:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
</beans>
那么我們就從annotation-config的解析開始
從代碼很容易看出,annotation-config的解析是在org.springframework.context.annotation.AnnotationConfigBeanDefinitionParser類里。
PostProcessor的注冊
對于annotation-config的處理,依然只關(guān)心最核心的部分。跟著源碼走,發(fā)現(xiàn)一部分非常核心的邏輯是在AnnotationConfigUtils里。在處理annotation-config時候,spring配置了各種PostProcessor類
ConfigurationClassPostProcessor
AutowiredAnnotationBeanPostProcessor
RequiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor
....
populateBean
我們在分析populateBean時候,只是曾跳過一段關(guān)于關(guān)于PostProcessor的回調(diào)方法。而Spring正是通過PostProcessor來實現(xiàn)注解方式的依賴注入的。
同樣,這里把PostProcessor這一段單獨貼出來
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
PropertyValues pvs = mbd.getPropertyValues();
if (bw == null) {
if (!pvs.isEmpty()) {
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.
boolean continueWithPropertyPopulation = true;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) {
return;
}
//... 省略AutowiredMode等
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
//就是在這里處理注解形式的依賴注入的
if (hasInstAwareBpps || needsDepCheck) {
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
applyPropertyValues(beanName, mbd, bw, pvs);
}
@Autowired處理 AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues
從annotatation-config的處理我們知道了,spring其實配置了很多的PostProcessor。這里我只分析我們最常用的一個AutowiredAnnotationBeanPostProcessor
這個類對@Autowired注解進(jìn)行了處理
AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues
隨后我們就來看看,究竟這個AutowiredAnnotationBeanPostProcessor是如何對這些依賴注入使用的注解進(jìn)行處理的
public PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
try {
metadata.inject(bean, beanName, pvs);
}
catch (BeanCreationException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
return pvs;
}
這里的代碼很簡單,找到InjectionMetadata
調(diào)用InjectionMetadata進(jìn)行注入
那么我們就要先弄清楚,這個InjectionMetadata究竟是什么?
Internal class for managing injection metadata.
Not intended for direct use in applications.
注釋里說是一個用于管理注入的元數(shù)據(jù)
的管理類,到這里我們還是不清楚它是干啥用的。
所以繼續(xù)深入分析InjectionMetadata是如何構(gòu)建的。findAutowiringMetadata這個方法大概就是,如果有的話,就從緩存獲取,如果沒有的話,就build一個。所以我們直接看build的邏輯就好了
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<>();
Class<?> targetClass = clazz;
do {
final LinkedList<InjectionMetadata.InjectedElement> currElements =
new LinkedList<>();
//找到所有的標(biāo)注了 @Autowired @Value 等注解的field,封裝成一個AutowiredFieldElement 添加到currElements里
ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() {
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
AnnotationAttributes ann = findAutowiredAnnotation(field);
if (ann != null) {
if (Modifier.isStatic(field.getModifiers())) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation is not supported on static fields: " + field);
}
return;
}
boolean required = determineRequiredStatus(ann);
currElements.add(new AutowiredFieldElement(field, required));
}
}
});
//找到所有的標(biāo)注了 @Autowired @Value 等注解的method,封裝成一個AutowiredFieldElement 添加到currElements里
ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
return;
}
AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (Modifier.isStatic(method.getModifiers())) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation is not supported on static methods: " + method);
}
return;
}
if (method.getParameterCount() == 0) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation should be used on methods with parameters: " + method);
}
}
boolean required = determineRequiredStatus(ann);
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
currElements.add(new AutowiredMethodElement(method, required, pd));
}
}
});
elements.addAll(0, currElements);
targetClass = targetClass.getSuperclass();
}
while (targetClass != null && targetClass != Object.class);
//封裝找到了的method和field,放到InjectionMetadata
return new InjectionMetadata(clazz, elements);
}
這里的邏輯也很簡單
1)找到所要注入的類,標(biāo)記有 @Autowired @Value等注解的 field和method 添加到一個list中
2)以list和這個class封裝成一個InjectionMetadata
3)注意這里的while (targetClass != null && targetClass != Object.class);
除了掃描自己類的@Autowired等注解,還會掃描父類的注解,這也解釋了,為什么繼承了抽象類的時候,可以同時繼承其 @Autowired等注解
下面的例子簡單說明了父類注入的場景
抽象類的注入
@Component
public class BaseDao {
//各種數(shù)據(jù)庫操作方式...
}
//抽象類,只是注入了dao
public abstract class BaseService {
@Autowired
protected BaseDao dao;
public BaseDao getDao() {
return dao;
}
public void setDao(BaseDao dao) {
this.dao = dao;
}
}
StudentService 繼承了BaseService,這樣就可以直接在自己的方法里使用dao
public class StudentService extends BaseService {
}
xml配置,xml只需要配置Service和dao,就會自動將dao注入到StudentService中
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--<context:component-scan base-package="com.hdj.learn.spring.annotation"/>-->
<bean id="dao" class="com.hdj.learn.spring.annotation.abs.BaseDao">
</bean>
<bean id="studentService" class="com.hdj.learn.spring.annotation.abs.StudentService"/>
<context:annotation-config/>
</beans>
@Autowired的繼承正是通過上文分析的,一個簡單的do while就實現(xiàn)了。
回到 InjectionMetadata
經(jīng)過上文的分析,我們就大概知道了所謂的InjectionMetadata究竟是個什么。它存儲了某個類,以及這個類里需要被依賴注入的element(標(biāo)注了@Autowired,@Value等注解的方法或者成員變量)
分析到這里后,隨后的就是InjectionMetadata.inject方法。
大概就是遍歷之前的List<InjectedElement> 然后調(diào)用 InjectedElement.inject方法
protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
Field field = (Field) this.member;
Object value;
if (this.cached) {
value = resolvedCachedArgument(beanName, this.cachedFieldValue);
}
else {
DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
desc.setContainingClass(bean.getClass());
Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
TypeConverter typeConverter = beanFactory.getTypeConverter();
try {
//找到要注入的值
value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
}
synchronized (this) {
if (!this.cached) {
if (value != null || this.required) {
this.cachedFieldValue = desc;
registerDependentBeans(beanName, autowiredBeanNames);
if (autowiredBeanNames.size() == 1) {
String autowiredBeanName = autowiredBeanNames.iterator().next();
if (beanFactory.containsBean(autowiredBeanName)) {
if (beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
this.cachedFieldValue = new ShortcutDependencyDescriptor(
desc, autowiredBeanName, field.getType());
}
}
}
}
else {
this.cachedFieldValue = null;
}
this.cached = true;
}
}
}
if (value != null) {
ReflectionUtils.makeAccessible(field);
field.set(bean, value);
}
}
特別熟悉的代碼,大體和之前通過xml依賴注入的代碼一樣。找到要注入的對象,注入進(jìn)去。
總結(jié)
這篇博客分析了spring對于注解標(biāo)記的變量,是如何進(jìn)行注入了。主要分析了我們最常用的 @Autowired 、@Value 注解。依賴注入分析到這里,基本上就能大致理解spring依賴注入的步驟。當(dāng)然還是有種無法統(tǒng)一的感覺,下一篇博客會試著從上層到下分析spring依賴注入究竟是如何設(shè)計的,以及從spring的依賴注入中我們能學(xué)到什么。