PropertyOverrideConfigurer

Spring的框架中为您提供了一个 BeanFactoryPostProcessor的实现类别:

org.springframework.beans.factory.config.PropertyOverrideConfigurer。藉由这个 类别,您可以在.properties中设定一些优先属性设定,这个设定如果与XML中的属性定义有相冲突,则以.properties中的设定为主。

举个例子来说,您可以如此设定Bean定义档:

  • beans-config.xml
   <?xml version="1.0" encoding="UTF-8"?> 
   <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" 
     "http://www.springframework.org/dtd/spring-beans.dtd"> 
   
   <beans>  
       <bean id="configBean" 
     class="org.springframework.beans.factory.config.PropertyOverrideConfigurer"> 
           <property name="location"> 
               <value>hello.properties</value> 
           </property> 
       </bean> 
   
       <bean id="helloBean" class="onlyfun.caterpillar.HelloBean"> 
           <property name="helloWord"> 
               <value>Hello!</value> 
           </property> 
       </bean>
   </beans>

在hello.properties中,您可以如下设定:

  • hello.properties
   helloBean.helloWord=Welcome!

helloBean对应于XML定义档中的某个Bean的id值,当中的helloWord设定将覆盖XML中的helloWord属性设定,如果您执行下面的程序,最后会显示"Welcome!",而不是"Hello!":

  • SpringDemo.java
   package onlyfun.caterpillar; 
   
   import org.springframework.context.ApplicationContext;
   import org.springframework.context.support.FileSystemXmlApplicationContext; 
   
   public class SpringDemo { 
       public static void main(String[] args) throws InterruptedException { 
           ApplicationContext context = 
               new FileSystemXmlApplicationContext("beans-config.xml");
            
           HelloBean hello = 
               (HelloBean) context.getBean("helloBean");
           System.out.println(hello.getHelloWord());
       } 
   }