不使用XML定義檔進行Bean設置


假設HelloBean的內容如下:
  • HelloBean.java
package onlyfun.caterpillar; 

public class HelloBean {
private String helloWord;

public HelloBean() {
}

public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
public String getHelloWord() {
return helloWord;
}
}

XML檔案的階層格式適用於於組態設定,也因此許多的開源專案都將XML作為預設的組態定義方式,但通常也會提供非XML定義檔的方式,像屬性檔案. properties,Spring也可以讓您使用屬性檔案定義Bean,例如定義一個beans-config.properties:
  • beans-config.properties
helloBean.class=onlyfun.caterpillar.HelloBean
helloBean.helloWord=Welcome!

屬性檔中helloBean名稱即是Bean的名稱,.class用於指定類別來源,其它的屬性就如.helloWord即屬性的名稱,可以使用 org.springframework.beans.factory.support.PropertiesBeanDefinitionReader 來讀取屬性檔,一個範例如下:
  • SpringDemo.java
package onlyfun.caterpillar; 

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;

public class SpringDemo {
public static void main(String[] args) {
BeanDefinitionRegistry reg =
new DefaultListableBeanFactory();
PropertiesBeanDefinitionReader reader =
new PropertiesBeanDefinitionReader(reg);
reader.loadBeanDefinitions(
new ClassPathResource("beans-config.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註冊,不使用任何 的檔案來定義的好處是,客戶端與定義檔是隔離的,他們無法接觸定義檔的內容,直接來看個例子:
  • SpringDemo.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 SpringDemo {
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());
}
}