0
点赞
收藏
分享

微信扫一扫

Spring源码解析 (谈谈@Autowried注解是怎么完成自动注入的) (九)

1.测试准备

Cat.java

@Component
public class Cat {
private String catName = "tomcat";

public String getCatName() {
return catName;
}

public void setCatName(String catName) {
this.catName = catName;
}


}

Person.java

通过set加上@Autowred注解注入

@Component
public class Person {

private Cat cat;

public Person() {
System.out.println("person创建");
}

public Cat getCat() {
return cat;
}

@Autowired
public void setCat(Cat cat) {
this.cat = cat;
}
}

MainConfig.java

@ComponentScan("com.atguigu")
@Configuration
public class MainConfig {
}

函数入口

@Test
public void testAutowire() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);

}

2.注解过程

简单的来说就是通过配置类的refresh加载容器, 然后创建出单例bean, 然后通过后置处理器的时候加载@Autowried注解, 完成解析和注入。

refresh() -> getBean -> doGetBean -> getSingleton -> createBean -> doCreateBean -> poputateBean -> AutowireAnnotationBeanPostProcessor的后置处理器干预

  1. AnnotationConfigApplication.java

public AnnotationConfigApplicationContext(Class... componentClasses) {
this();
register(componentClasses);
refresh();
}

Spring源码解析 (谈谈@Autowried注解是怎么完成自动注入的) (九)_ide

  1. AbstractApplicationContext.java
    finishBeanFactoryInitialization() -> preInstantiateSingletons()

@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
...
try {
...
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
...
}

catch (BeansException ex) {
...
}
...
}
finally {
...
}
}
}

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
...
// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();
}

  1. DefaultListableBeanFactory.java
    preInstantiateSingletons()

@Override
public void preInstantiateSingletons() throws BeansException {
...
if (isEagerInit) {
getBean(beanName);
}
}
}
else {
getBean(beanName);
}
}
}

  1. AbstractBeanFactory.java
    getBean() -> doGetBean()

@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}

protected <T> T doGetBean(
String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException {

String beanName = transformedBeanName(name);//提取对应的beanName
Object bean;

// Eagerly check singleton cache for manually registered singletons.尝试从缓存获取或者singletonFactories中的ObjectFactory中获取
检查缓存中是否存在,寻找的是DefaultSingletonBeanRegistry里的singletonObjects map是否含有对应的Object
// //DefaultListableBeanFactory是DefaultSingletonBeanRegistry的子类,DefaultSingletonBeanRegistry类中存放了很多map,用于存储bean的信息,IOC容器的单例池存放的地方
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
...

...

try {
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);

// Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
...
}
}

// Create bean instance.创建bean的实例
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args); //创建bean对象的实例
}
catch (BeansException ex) {
...
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}

else if (mbd.isPrototype()) {
...
}

else {
...
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}

// Check if required type matches the type of the actual bean instance.
...
return (T) bean;
}

这里是一个lambda表达式的getSingleton()

  1. DefaultSingletonBeanRegistry.java
    getSingleton()

public Object getSingleton(String beanName, ObjectFactory singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
...
try {
singletonObject = singletonFactory.getObject();ObjectFactory提供Bean实例,此处的getObect是上一步sharedInstance = getSingleton(...)的lambda表达式 createBean(beanName, mbd, args)
newSingleton = true;
}
...
}
return singletonObject;
}
}

  1. AbstractAutowireCapableBeanFactory.java
    createBean() -> doCreateBean() -> populateBean()

@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {

...

try {
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
...
return beanInstance;
}
...
}




protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {

// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//创建bean实例
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
...

...

// Initialize the bean instance.
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
...
}

...

return exposedObject;
}




protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
...

//让任何 InstantiationAwareBeanPostProcessors 有机会在设置属性之前修改 bean 的状态。例如,这可以用于支持字段注入的样式。
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
}

PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

...

boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

if (hasInstAwareBpps || needsDepCheck) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {//如果有aware注解,则调用含有aware的后置处理器,对aware的属性进行赋值
for (BeanPostProcessor bp : getBeanPostProcessors()) {
//此处拿到的bp是AutowiredAnnotationBeanPostProcessor
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);//通过后置处理器对属性进行增强,也就是对标注了@Autowire注解的属性进行注入
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}

if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);//xml版的所有配置一般来到这给属性赋值
}
}

  1. AutowireAnnotationBeanPostProcessor.java
    postProcessPropertyValues() -> findAutowiringMetadata() -> buildAutowiringMetadata() -> findAutowiredAnnotation()
    找到含有注解的类或方法

后置处理器

@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;
}

找到元注解

private InjectionMetadata findAutowiringMetadata(String beanName, Class clazz, @Nullable PropertyValues pvs) {
// Fall back to class name as cache key, for backwards compatibility with custom callers.
String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
// Quick check on the concurrent map first, with minimal locking.
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;
}

通过元注解找到注解方法或者类

private InjectionMetadata buildAutowiringMetadata(final Class clazz) {
if (!AnnotationUtils.isCandidateClass(clazz, this.autowiredAnnotationTypes)) {
return InjectionMetadata.EMPTY;
}

List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
Class targetClass = clazz;

do {
final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();

ReflectionUtils.doWithLocalFields(targetClass, field -> {
MergedAnnotation ann = findAutowiredAnnotation(field);
if (ann != null) {
if (Modifier.isStatic(field.getModifiers())) {
if (logger.isInfoEnabled()) {
logger.info("Autowired annotation is not supported on static fields: " + field);
}
return;
}
boolean required = determineRequiredStatus(ann);
currElements.add(new AutowiredFieldElement(field, required));
}
});

ReflectionUtils.doWithLocalMethods(targetClass, method -> {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
return;
}
MergedAnnotation ann = findAutowiredAnnotation(bridgedMethod);
if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (Modifier.isStatic(method.getModifiers())) {
if (logger.isInfoEnabled()) {
logger.info("Autowired annotation is not supported on static methods: " + method);
}
return;
}
if (method.getParameterCount() == 0) {
if (logger.isInfoEnabled()) {
logger.info("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 InjectionMetadata.forElements(elements, clazz);
}

找到具体类或者方法的方法

@Nullable
private MergedAnnotation findAutowiredAnnotation(AccessibleObject ao) {
MergedAnnotations annotations = MergedAnnotations.from(ao);
for (Class extends Annotation> type : this.autowiredAnnotationTypes) {
MergedAnnotation annotation = annotations.get(type);
if (annotation.isPresent()) {
return annotation;
}
}
return null;
}

其中this.autowiredAnnotationTypes的定义如下:

this.autowiredAnnotationTypes.add(Autowired.class);
this.autowiredAnnotationTypes.add(Value.class);

所以说最后是AutowireAnnotationBeanPostProcessor这个后置处理器找到了注解的方法或类

最后通过InjectionMetadata.inject执行注入

  1. InjectionMetadata.java
    inject()

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()) {
//遍历所有的注入源信息类利用反射赋值,每个element中含有反射需要调用的方法
for (InjectedElement element : elementsToIterate) {
if (logger.isDebugEnabled()) {
logger.debug("Processing injected element of bean '" + beanName + "': " + element);
}
element.inject(target, beanName, pvs);
}
}
}

  1. AutowireAnnotationBeanPostProcessor.java
    inject()

@Override
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
Field field = (Field) this.member;
Object value;
if (this.cached) {
try {
value = resolvedCachedArgument(beanName, this.cachedFieldValue);
}
catch (NoSuchBeanDefinitionException ex) {
// Unexpected removal of target bean for cached argument -> re-resolve
value = resolveFieldValue(field, bean, beanName);
}
}
else {
value = resolveFieldValue(field, bean, beanName);
}
if (value != null) {
ReflectionUtils.makeAccessible(field);
field.set(bean, value);
}
}

最后通过反射注入set方法
Person.java

@Autowired
public void setCat(Cat cat) {
this.cat = cat;
}

这里的InjectedElement为装饰者模式。

Spring源码解析 (谈谈@Autowried注解是怎么完成自动注入的) (九)_ide_02
Spring源码解析 (谈谈@Autowried注解是怎么完成自动注入的) (九)_java_03

举报

相关推荐

0 条评论