入门 08 - 不使用XML定义档
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与上面这个程序就可以运作了,不需要任何其它的档案。