PropertyPlaceHolderConfigurer中的location是不是用错了?

未来已来2018-12-14 13:41

本文由作者张远道授权网易云社区发布。


spring中常用PropertyPlaceHolderConfigurer来读取properties配置文件的配置信息。常用的配置方式有两种,一种是使用location


<bean id="property" >
    <property="location" value="classpath:myproperty.propeties"/>
</bean>


 另一种是使用locations


<bean id="property" 
<property="locations">
<list>
<value>classpath:myproperty.propeties</value>
<value>classpath:myproperty1.properties</value>
</list>
</property>
</bean>


查看PropertyPlaceHolderConfigurer的源码发现,整个PropertyPlaceHolderConfigurer的继承树中都没有location整个属性,仅仅只有locations这个属性。如下图所示。

因此,认为既然没有location这个属性,那使用时是不是不正确。但是仔细看看发现了PropertiesLoaderSupport中有setLocation()方法。

而查看spring有关依赖注入的源码:

即获得property对应的setter方法,以及property对应的值,然后通过反射,调用该方法即可。可以看出,不要求类的定义中真正包含改属性,只要对应的setter方法被调用即可以。因此,ioc容器从xml配置中读到属性为location的值,然后获得location对应的setter方法,即setLocation,然后通过反射,将location的值传入了setLocation中。如下图。

结论:location属性没有使用错,而是spring根据反射调用setLocation方法,将location赋值给了locations了而已。


免费领取验证码、内容安全、短信发送、直播点播体验包及云服务器等套餐

更多网易技术、产品、运营经验分享请访问网易云社区


相关文章:
【推荐】 玩转数据产品设计-小屏幕下的大数据
【推荐】 一个体验好的Windows 任务栏缩略图开发心得
【推荐】 Flink on Yarn模式启动流程分析