Spring5的@Autowire原理分析
Autowire注解
从Autowire注解点进去看
注释的第一句话说是将构造函数、字段、setter方法或者配置方法通过由Spring依赖注入工具自动装入
在注释的最后 说这个注解是通过 BeanPostProcessor 这个接口进行的
最后的实现类是 AutowiredAnnotationBeanPostProcessor
AutowiredAnnotationBeanPostProcessor 类
public class AutowiredAnnotationBeanPostProcessor
extends InstantiationAwareBeanPostProcessorAdapter
implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware
- InstantiationAwareBeanPostProcessorAdapter能够设置Bean的属性值
- PriorityOrdered接口用于标识这个类的创建的优先级
- BeanFactoryAware接口用于获取Spring的BeanFactory
- MergedBeanDefinitionPostProcessor:合并Bean定义后置处理器(继承BeanPostProcessor)
构造函数
在创建的时候会把Autowired和Value设置到autowiredAnnotationTypes这个列表中,如果存在@Inject这个注解也同样会被塞进去
private final Set<Class<? extends Annotation>> autowiredAnnotationTypes = new LinkedHashSet<>();
public AutowiredAnnotationBeanPostProcessor() {
this.autowiredAnnotationTypes.add(Autowired.class);
this.autowiredAnnotationTypes.add(Value.class);
try {
this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
logger.info("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
}
catch (ClassNotFoundException ex) {
// JSR-330 API not available - simply skip.
}
}
运行过程
在容器执行的时候会调用refresh()方法,里面有个registerBeanPostProcessor方法,
会对AutowiredAnnotationBeanPostProcessor进行一个注册
之后会执行finishBeanFactoryInitialization(beanFactory)方法对非延迟初始化的单例bean进行初始化时,
会执行到AbstractAutowireCapableBeanFactory的createBean方法,并且调用doCreateBean方法创建Bean,
会调用MergedBeanDefinitionPostProcessor接口的postProcessMergedBeanDefinition方法
/**
* 这个方法是对注入属性的创建
*/
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
// 在此之后会调用populateBean这个方法
// 在postProcessPropertyValues中才是最后把属性给写出去
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
所以说,我们需要从postProcessMergedBeanDefinition这个方法开始看起
首先先定义了三个测试类:
@RestController
public class DemoController {
@Autowired
private DemoService demoService;
@RequestMapping("/")
String home() {
return demoService.getString();
}
}
@Service
public class DemoService {
public String getString() {
return "Hello World!";
}
}
@SpringBootApplication
public class SampleController {
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleController.class, args);
}
}
在启动的时候,Spring会寻找每个Bean,并且调用postProcessMergedBeanDefinition为他们注入还有@Autowire的属性
[图片上传失败...(image-e85ff9-1530195131381)]
这里算是预处理部分,将注入列表给弄出来
/**
* 最终缓存列表的地方
*/
public void checkConfigMembers(RootBeanDefinition beanDefinition) {
Set<InjectedElement> checkedElements = new LinkedHashSet<>(this.injectedElements.size());
for (InjectedElement element : this.injectedElements) {
Member member = element.getMember();
if (!beanDefinition.isExternallyManagedConfigMember(member)) {
beanDefinition.registerExternallyManagedConfigMember(member);
checkedElements.add(element);
if (logger.isDebugEnabled()) {
logger.debug("Registered injected element on class [" + this.targetClass.getName() + "]: " + element);
}
}
}
this.checkedElements = checkedElements;
}
private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
// 接下来的操作会锁资源,所以先进行一遍查找,如果查询出来的没有被处理过才进行处理
InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
synchronized (this.injectionMetadataCache) {
metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
if (metadata != null) {
metadata.clear(pvs);
}
// 构造需要注入的元素
metadata = buildAutowiringMetadata(clazz);
// 将处理过的给缓存起来
this.injectionMetadataCache.put(cacheKey, metadata);
}
}
}
return metadata;
}
public static boolean needsRefresh(@Nullable InjectionMetadata metadata, Class<?> clazz) {
return (metadata == null || metadata.targetClass != clazz);
}
/**
* 构造需要注入的元素
*
*/
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<>();
Class<?> targetClass = clazz;
do {
final LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<>();
// 循环这个类的所有属性
ReflectionUtils.doWithLocalFields(targetClass, field -> {
// 寻找含有在autowiredAnnotationTypes注解列表里面的属性
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);
// 当前的属性表加入一个新的需要注入的属性
// 其实就是把DemoService放到这个列表中作为备用
currElements.add(new AutowiredFieldElement(field, required));
}
});
// 这段就是寻找还有包含自动注入的方法
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
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 only 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);
// 最后返回一个这个类需要注入的列表出去
return new InjectionMetadata(clazz, elements);
}
最后将属性注入到Bean中
@Override
public PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException {
// 由于在上一步就已经进行了创建所以这不会再进行创建,直接把列表返回
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;
}
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);
}
}
}
@Override
protected void inject(Object bean, @Nullable String beanName, @Nullable 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);
Assert.state(beanFactory != null, "No BeanFactory available");
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) &&
beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
this.cachedFieldValue = new ShortcutDependencyDescriptor(
desc, autowiredBeanName, field.getType());
}
}
}
else {
this.cachedFieldValue = null;
}
this.cached = true;
}
}
}
// 上面都是执行各种构造,最终是使用反射将值塞到对应的Bean里面
if (value != null) {
ReflectionUtils.makeAccessible(field);
field.set(bean, value);
}
}
[图片上传失败...(image-d50582-1530195131381)]
END