简单记录一下今天学到的关于容器扩展机制的知识点
共接触到俩个,一个是PropertyPlaceholderConfigurer,简言之就是通过占位符解决xml中配置修改的问题,一般来说我们希望xml文件里面放跟业务相关性大的bean,一般像连接数据库等资源分开放比较好,一般我们会放在peoperties文件下,有了PropertyPlaceholderConfigurer就能帮我们做到这一点,具体例子如下:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="username">
<value>${jdbc.username}</value>
</property>
....
</bean>
如果我们不用PropertyPlaceholderConfigurer,那么url的值就是${jdbc.url},同理username也是一样的结果,在使用PropertyPlaceholderConfigurer之前需先在xml中配置,如下:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>"../jdbc.properties"</value>
</property>
<bean>
上面指出了PropertyPlaceholderConfigurer的properties配置文件的位置,我们将会把该配置文件中的内容替换上面占位符所指定的内容。
jdbc.properties内容如下:
jdbc.url=jdbc:mysql://.....
jdbc.username=XXX
这样我们最后得到的dataSource的属性内容就是该配置文件中的内容。
另一个就是PropertyOverrideConfigurer,这个就是根据properties文件中指定xml文件中的beanName直接替换,bean的id就是beanName。
使用PropertyPlaceholderConfigurer之前需先在xml中配置,如下:
<bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
<property name="location">
<value>"../pool-adjustment.properties"</value>
</property>
<bean>
pool-adjustment.properties文件配置如下:
dataSource.url=jdbc:mysql://.....
dataSource.username=XXX
总之,我们可以通过BeanFactoryPostProcessor的实现类实现xml中bean属性内容的替换