Spring入门08 - 不使用XML定义档

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值