小弟我的spring学习笔记15-容器扩展点之PropertyOverrideConfigurer
我的spring学习笔记15-容器扩展点之PropertyOverrideConfigurer
PropertyOverrideConfigurer类似于PropertyPlaceholderConfigurer,但是与后者相比,前者对于bean属性可以有缺省值或者根本没有值。也就是说如果properties文件中没有某个bean属性的内容,那么将使用上下文(配置的xml文件)中相应定义的值。如果properties文件中有bean属性的内容,那么就用properties文件中的值来代替上下文中的bean的属性值。
首先看一下配置文件,代码如下:
其中student类,在前面已经给出了代码,这里不再叙述。
接着是,properties文件的代码:
student.age=27
student.birth=19820123
测试用的主类的代码如下:
由于配置文件中已经有name属性的值,而properties文件中没有,所以执行后的结果是:
27
19820123
Xiaohailin
如果把properties文件改一下:修改之后的代码如下:
student.age=27
student.birth=19820123
student.name=jiangmin
那么测试主类执行后的结果如下:
student.age=27
student.birth=19820123
student.name=jiangmin
PropertyOverrideConfigurer类似于PropertyPlaceholderConfigurer,但是与后者相比,前者对于bean属性可以有缺省值或者根本没有值。也就是说如果properties文件中没有某个bean属性的内容,那么将使用上下文(配置的xml文件)中相应定义的值。如果properties文件中有bean属性的内容,那么就用properties文件中的值来代替上下文中的bean的属性值。
首先看一下配置文件,代码如下:
<bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer"> <property name="location" value="propertyOverrideHolder.properties"/> </bean> <bean id ="student" class="co.jp.beanFactoryPost.Student"> <property name="name"> <value>Xiaohailin</value> </property> <property name="age"> <value>${age}</value> </property> <property name="birth"> <value>${birth}</value> </property> </bean>
其中student类,在前面已经给出了代码,这里不再叙述。
接着是,properties文件的代码:
student.age=27
student.birth=19820123
测试用的主类的代码如下:
public class PropertyOverrideConfigurerDemo { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("propertyOverrideHolder.xml"); Student student = (Student) ctx.getBean("student"); System.out.println(student.getAge()); System.out.println(student.getBirth()); System.out.println(student.getName()); } }
由于配置文件中已经有name属性的值,而properties文件中没有,所以执行后的结果是:
27
19820123
Xiaohailin
如果把properties文件改一下:修改之后的代码如下:
student.age=27
student.birth=19820123
student.name=jiangmin
那么测试主类执行后的结果如下:
student.age=27
student.birth=19820123
student.name=jiangmin