Spring笔记之一Bean的标志符(id与name)

一般来说,在一个XmlBeanFactory中,定义一个bean时,采用的是<bean id="XX" class="XX">的样式,如<bean id="helloBean" class="javamxj.HelloBean">。
这里id的命名格式必须符合XML ID属性的命名规范,例如,不能以数字开头,“222”就不是合法的id值。为了解决这个问题,可以使用name属性指定一个和多个id(用逗号或者分号隔离)。  

HelloBean.java
package javamxj . spring . basic . aliases ;

public class HelloBean {

    private String helloWorld = "Hello!World!";

    public void setHelloWorld( String helloWorld) {
        this.helloWorld = helloWorld;
    }

    public String getHelloWorld() {
        return helloWorld;
    }

}
 
· 配置文件
    在这个Bean中,除了id属性,还含有name属性,其值为“2hello”、 “[email protected] ”,因为以数字开头、含有特殊字符“@”,它们是不能用在id属性中的 
bean.xml
<? xml version="1.0" encoding= "GBK" ?>
<! DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd" >

< beans >
    < bean id= " helloBean " name= " 2hello,[email protected] "
        class= " javamxj.spring.basic.aliases.HelloBean " >
        < property name= " helloWorld " >
            < value >Hello! Javamxj! </ value >
        </ property >
    </ bean >
</ beans >
 
· 测试程序:
Main.java
package javamxj . spring . basic . aliases ;

import org . springframework . beans . factory . BeanFactory ;
import org . springframework . beans . factory . xml . XmlBeanFactory ;
import org . springframework . core . io . ClassPathResource ;
import org . springframework . core . io . Resource ;

public class Main {
    public static void main( String[] args) {

        Resource res = new ClassPathResource( "javamxj/spring/basic/aliases/bean.xml");
        BeanFactory factory = new XmlBeanFactory(res);

        HelloBean helloBean  = (HelloBean) factory.getBean( "helloBean");
        HelloBean helloBean2 = (HelloBean) factory.getBean( "2hello");
        HelloBean helloBean3 = (HelloBean) factory.getBean( "[email protected]");

        System.out.println(helloBean.getHelloWorld());

        // 验证是否指向同一个Bean
        System.out.println((helloBean == helloBean2));
        System.out.println((helloBean == helloBean3));

        // 输出这个Bean的别名
        String[] aliases = factory.getAliases( "helloBean");
        for ( String str : aliases) {
            System.out.println(str);
        }
    }
}
可以看出,使用中id属性和name属性几乎没有任何区别。
 
  调用BeanFactory.getAliases(String)的方法时,传入的参数可以是任意一个Bean名字,输出的别名则是除去id之外的所有Bean名,如果没有指定id,则将其name属性中的第一个值指定为id。
 
  当然,Bean的name属性不仅仅只是为了输入id属性所不允许的名字,它还有其它的用处,

你可能感兴趣的:(spring,bean,String,System,Class,import)