美文网首页
【Spring源码配置文件解析】2. xml注入配置信息 & @

【Spring源码配置文件解析】2. xml注入配置信息 & @

作者: 天还下着毛毛雨 | 来源:发表于2020-12-30 15:10 被阅读0次

xml方式往bean注入配置信息

配置文件application.properties

person.name=liuben
person.password=123456
value=giao

application.xml

image

Person类

image

这样xml中配置的bean的属性就会被注入配置文件里面对应的值

xml方式源码解析:

首先xml中的bean会在扫描的过程中封装成BeanDefinition对象,property标签会被弄成一个ProprotyValue的集合放在BeanDefinition的ProprotyValues变量中,所以在xml解析完成之后的BeanDefinition的ProprotyValues变量是这样的

image

上节PropertySourcesPlaceholderConfigurer这个类收集了environment配置信息和本地配置信息,并把它放在了PropertySourcesPropertyResolver的propertySources属性中

image

最后创建了一个StringValueResolver对象会调用PropertySourcesPropertyResolver来处理配置信息的替换

image

接下来就是取出所有的BeanDefinition,看看beanDefinition中的属性中是否有${}表达式,有的话就替换

image

很多的属性都可以用${}来引用配置信息

ParentName
BeanClassName
FactoryBeanName
FactoryMethodName
Scope
PropertyValues 
ConstructorArgumentValues //构造方法参数
image

重点看看属性是如何被替换的

image

需要将${person.name} 替换成配置信息中的值

image

在BeanDefinitionVisitor.resolveValue方法中,String类型的走这

image

最终会调到PropertySourcesPlaceholderConfigurer创建的StringValueResolver匿名对象的实现方法中

image image

这个匿名对象实现的方法又会调用PropertySourcesPropertyResolver来替换值,前面有提到所有的配置信息都在PropertySourcesPropertyResolver.propertySources中,那么接下来的工作就是从这个容器中找到对应的配置信息的key所对应的value

image

这里在入参时会创建一个PlaceholderResolver的匿名对象,实现的resolvePlaceholder方法将会调用PropertySourcesPropertyResolver.getPropertyAsRawString()

image image image

最后返回了被替换成对应配置信息的值


image

这里就会调用前面创建的匿名对象的实现方法,方法体重会调用调用PropertySourcesPropertyResolver.getPropertyAsRawString(),去用key获取对应的配置信息

image

PropertySourcesPropertyResolver.getPropertyAsRawString()


image

PropertiesPropertySource对象内部有name,和source,source是一个泛型,当前类型为Properties,PropertiesPropertySource需要实现getProperty方法,其实就是从source中获取属性值

image

最后调到了Properties类的get方法,返回value

获取到替换后的值,重新以k-v的形式往BD的propertyValues里加

image

对每个beanDefination都这样操作过一遍

处理Bean的别名

image image

最后将StringValueResolver对象放到BeanFactory的embeddedValueResolvers容器中

注意这个StringValueResolver的resolveStringValue会调用PropertySourcesPropertyResolver的方法来处理配置信息的替换,PropertySourcesPropertyResolver持有了所有的配置信息。 那么后面@Value的解析也将StringValueResolver来完成

image image

@Value源码解析:

@Value的解析工作是在Bean实例化后,属性注入的时候从配置文件找出并设置进去的

image image

populateBean方法

image image image image

只有string类型的才能@Value注解,才需要处理

image

又是这个容器,之前PropertySourcesPlaceholderConfigurer的doProcessProperties放进去的StringValueResolver

image

最后又会回到这个地方解析并注入值,和xml方式获取配置信息是一样的


image

找到对应的配置信息之后,反射设置这个属性的值

image

相关文章

网友评论

      本文标题:【Spring源码配置文件解析】2. xml注入配置信息 & @

      本文链接:https://www.haomeiwen.com/subject/vuehoktx.html