Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Spring中Bean的命名问题(id和name区别)及ref和idref之间的区别

Spring中Bean的命名1、每个Bean可以有一个id属性,并可以根据该id在IoC容器中查找该Bean,该id属性值必须在IoC容器中唯一;2、可以不指定id属性,只指定全限定类名,如:<bean class="com.zyh.spring3.hello.StaticBeanFactory"></bean>此时需要通过接口getBean(Class<T> requiredType)来获取Bean;如果该Bean找不到则抛异常:NoSuchBeanDefinitionException如果该类型的Bean有多个则抛异常:NoUniqueBeanDefinitionException3、如果不指定id,只指定name,那么name为Bean的标识符,并且需要在容器中唯一;4、同时指定name和id,此时id为标识符,而name为Bean的别名,两者都可以找到目标Bean;5、可以指定多个name,之间可以用分号(“;”)、空格(“ ”)或逗号(“,”)分隔开,如果没有指定id,那么第一个name为标识符,其余的为别名;若指定了id属性,则id为标识符,所有的name均为别名。如:<bean name="alias1 alias2;alias3,alias4" id="hello1" class="com.zyh.spring3.hello.HelloWorld">
 <constructor-arg index="0" value="Rod"></constructor-arg>
</bean>此时,hello1为标识符,而alias1,alias2,alias3,alias4为别名,它们都可以作为Bean的键值;6、可以使用<alias>标签指定别名,别名也必须在IoC容器中唯一,如:<bean name="bean" class="com.zyh.spring3.hello.HelloWorld"/> 
<alias alias="alias1" name="bean"/> 
<alias alias="alias2" name="bean"/>ref和idref之间的区别在Spring中,idref属性和ref属性都可以用在constructor-arg元素和property元素中完成注入,那么它之间有什么区别呢?考虑如下一段配置:<bean id="bea" class="java.lang.String">
 <constructor-arg index="0"><value>testString</value></constructor-arg>
</bean>
<bean id="beanID" class="com.zyh.spring3.hello.HelloWorld">
 <constructor-arg name="name"><idref bean="bea" /></constructor-arg>
 <property name="id">
  <ref local="bea" />
 </property>
 <property name="age" value="25"></property>
</bean>其实,idref注入的是目标bean的id而不是目标bean的实例,同时使用idref容器在部署的时候还会验证这个名称的bean是否真实存在。其实idref就跟value一样,只是将某个字符串注入到属性或者构造函数中,只不过注入的是某个Bean定义的id属性值。所以上面的代码中<constructor-arg name="name"><idref bean="bea" /></constructor-arg>其实等同于<constructor-arg name="name"><value>bea</value></constructor-arg>而ref则是完全地不同,ref元素是将目标Bean定义的实例注入到属性或构造函数中,ref元素有三个属性,区别如下:1、local 只能指定与当前配置的Bean在同一个配置文件中的Bean定义的名称;
2、parent 只能指定位于当前容器的父容器中定义的对象引用;
3、bean 基本上通吃,即包括以上两种情况都可以,所以,通吃情况下,直接使用bean来指定对象引用就可以了。
所以,上面那段配置代码中,beanID这个Bean中构造函数的参数name注入的只是“bea”这个字符串;而其id属性注入的则是testString这个字符串。Spring中如何配置Hibernate事务 http://www.linuxidc.com/Linux/2013-12/93681.htmStruts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htm基于 Spring 设计并实现 RESTful Web Services http://www.linuxidc.com/Linux/2013-10/91974.htmSpring-3.2.4 + Quartz-2.2.0集成实例 http://www.linuxidc.com/Linux/2013-10/91524.htm使用 Spring 进行单元测试 http://www.linuxidc.com/Linux/2013-09/89913.htm运用Spring注解实现Netty服务器端UDP应用程序 http://www.linuxidc.com/Linux/2013-09/89780.htmSpring 3.x 企业应用开发实战 PDF完整高清扫描版+源代码 http://www.linuxidc.com/Linux/2013-10/91357.htmSpring 的详细介绍:请点这里
Spring 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-01/111391.htm