Spring的框架中為您提供了一個 BeanFactoryPostProcessor的
實作類別:org.springframework.beans.factory.config.PropertyOverrideConfigurer。藉由這個
類別,您可以在.properties中設定一些優先屬性設定,這個設定如果與XML中的屬性定義有相衝突,則以.properties中的設定為主。
舉個例子來說,您可以如此設定Bean定義檔:
<?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中,您可以如下設定:
helloBean.helloWord=Welcome!
helloBean對應於XML定義檔中的某個Bean的id值,當中的helloWord設定將覆蓋XML中的helloWord屬性設定,如果您執行下面的程式,最後會顯示"Welcome!",而不是"Hello!":
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()); } }
|