入門 08 - 不使用XML定義檔 <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
XML檔案的階層格式非常適用於於組態設定,也因此幾乎所有的開源項目都將XML作爲預設的組態定義方式,但通常也會提供非XML定義文件的方式,像屬性檔案.properties,Spring也可以讓您使用屬性檔案定義bean:
helloBean.class=onlyfun.caterpillar.HelloBean
helloBean.helloWord=Hello!Justin!
helloBean名稱即是Bean的別名,.class用於指定類別來源,其它的屬性就如.helloWord即setter的名稱,我們可以使用 org.springframework.beans.factory.support.PropertiesBeanDefinitionReader 來讀取屬性文件,一個範例如下:
SpringTest.java
package onlyfun.caterpillar;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.core.io.ClassPathResource;
public class SpringTest {
public static void main(String[] args) {
BeanDefinitionRegistry reg = new DefaultListableBeanFactory();
PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(reg);
reader.loadBeanDefinitions(new ClassPathResource("bean.properties"));
BeanFactory factory = (BeanFactory) reg;
HelloBean hello = (HelloBean) factory.getBean("helloBean");
System.out.println(hello.getHelloWord());
}
}
除了透過XML或屬性檔案,您也可以在程序中直接編程,透過 org.springframework.beans.MutablePropertyValues設置屬性,將屬性與Bean的類別設定給 org.springframework.beans.factory.support.RootBeanDefinition,並向 org.springframework.beans.factory.support.BeanDefinitionRegistry註冊,不使用任何的檔案來定義的好處是,客戶端與定義檔是隔離的,它們無法接觸定義檔的內容,直接來看個例子:
SpringTest.java
package onlyfun.caterpillar;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.MutablePropertyValues;
public class SpringTest {
public static void main(String[] args) {
// 設置屬性
MutablePropertyValues properties = new MutablePropertyValues();
properties.addPropertyValue("helloWord", "Hello!Justin!");
// 設置Bean定義
RootBeanDefinition definition = new RootBeanDefinition(HelloBean.class, properties);
// 註冊Bean定義與Bean別名
BeanDefinitionRegistry reg = new DefaultListableBeanFactory();
reg.registerBeanDefinition("helloBean", definition);
BeanFactory factory = (BeanFactory) reg;
HelloBean hello = (HelloBean) factory.getBean("helloBean");
System.out.println(hello.getHelloWord());
}
}
只要有spring-core.jar、commons-logging.jar與上面這個程序就可以運作了,不需要任何其它的檔案。