Spring配置文件中使用bean id和name的区别 [英] Difference between using bean id and name in Spring configuration file

查看:26
本文介绍了Spring配置文件中使用bean id和name的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Spring 配置文件中的 元素上使用 id 属性和 name 属性有什么区别吗?

Is there any difference between using an id attribute and name attribute on a <bean> element in a Spring configuration file?

推荐答案

来自 Spring 参考3.2.3.1 命名 Bean:

每个 bean 都有一个或多个 id(也称为标识符或名称;这些术语指的是同一件事).这些id 必须是唯一的承载 bean 的容器. Abean 几乎总是只有一个id,但如果一个 bean 有多个id,额外的基本上可以是视为别名.

Every bean has one or more ids (also called identifiers, or names; these terms refer to the same thing). These ids must be unique within the container the bean is hosted in. A bean will almost always have only one id, but if a bean has more than one id, the extra ones can essentially be considered aliases.

使用基于 XML 的配置时元数据,您使用id"或name"指定 bean 的属性身份标识).'id' 属性允许您指定一个 ID,因为它是一个真正的 XML 元素 ID属性,XML 解析器能够其他时候做一些额外的验证元素引用 id;因此,它是指定 bean 的首选方式ID.但是,XML 规范确实限制了字符在 XML ID 中合法.这通常不是一个限制,但如果你有需要使用这些特殊的 XML 之一人物,或者想介绍其他bean 的别名,您也可以或而是指定一个或多个 bean id,用逗号 (,)、分号分隔(;) 或名称"中的空格属性.

When using XML-based configuration metadata, you use the 'id' or 'name' attributes to specify the bean identifier(s). The 'id' attribute allows you to specify exactly one id, and as it is a real XML element ID attribute, the XML parser is able to do some extra validation when other elements reference the id; as such, it is the preferred way to specify a bean id. However, the XML specification does limit the characters which are legal in XML IDs. This is usually not a constraint, but if you have a need to use one of these special XML characters, or want to introduce other aliases to the bean, you may also or instead specify one or more bean ids, separated by a comma (,), semicolon (;), or whitespace in the 'name' attribute.

所以基本上 id 属性符合 XML id 属性标准,而 name 更灵活一些.一般来说,我几乎只使用 name.它似乎更春天".

So basically the id attribute conforms to the XML id attribute standards whereas name is a little more flexible. Generally speaking, I use name pretty much exclusively. It just seems more "Spring-y".

这篇关于Spring配置文件中使用bean id和name的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆