Spring 5.0.8.RELEASE文档 Core1-1.4.2 详细的依赖关系和配置

版权声明:mj1001001 https://blog.csdn.net/qq_42786889/article/details/82257568

As mentioned in the previous section, you can define bean properties and constructor arguments as references to other managed beans (collaborators), or as values defined inline. Spring’s XML-based configuration metadata supports sub-element types within its and elements for this purpose.

正如上一节中提到的,您可以将bean属性和构造函数参数定义为对其他托管bean(合作者)的引用,或者作为内联定义的值(类似value 1)。Spring的基于xml的配置元数据支持其内部使用子标签和 以实现此目的。

Straight values (primitives, Strings, and so on)
The value attribute of the element specifies a property or constructor argument as a human-readable string representation. Spring’s conversion service is used to convert these values from a String to the actual type of the property or argument.

直接值(原语、字符串等)
元素的value属性指定属性或构造器参数作为人类可读的字符串表示。Spring的conversion service(转换服务)用于将这些值从字符串转换为实际的类型。

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <!-- results in a setDriverClassName(String) call -->
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
    <property name="username" value="root"/>
    <property name="password" value="masterkaoli"/>
</bean>

The following example uses the p-namespace for even more succinct XML configuration.

下面的例子使用了p名称空间来实现更简洁的XML配置。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close"
        p:driverClassName="com.mysql.jdbc.Driver"
        p:url="jdbc:mysql://localhost:3306/mydb"
        p:username="root"
        p:password="masterkaoli"/>

</beans>

The preceding XML is more succinct; however, typos are discovered at runtime rather than design time, unless you use an IDE such as IntelliJ IDEA or the Spring Tool Suite (STS) that support automatic property completion when you create bean definitions. Such IDE assistance is highly recommended.

前面的XML更简洁;然而,在运行时而不是设计时发现了拼写错误,除非您使用了诸如IntelliJ IDEA或Spring Tool Suite(STS)这样的IDE,当您创建bean定义时,它支持自动属性完成。这种IDE的帮助是非常推荐的。

You can also configure a java.util.Properties instance as:

您还可以配置java.util.Properties 实例:

<bean id="mappings"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

    <!-- typed as a java.util.Properties -->
    <property name="properties">
        <value>
            jdbc.driver.className=com.mysql.jdbc.Driver
            jdbc.url=jdbc:mysql://localhost:3306/mydb
        </value>
    </property>
</bean>

The Spring container converts the text inside the element into a java.util.Properties instance by using the JavaBeans PropertyEditor mechanism. This is a nice shortcut, and is one of a few places where the Spring team do favor the use of the nested element over the value attribute style.

Spring容器将 元素中的文本转换成java.util.Properties实例,使用JavaBeans PropertyEditor机制。这是一个很好的快捷方式,也是Spring团队喜欢在中使用 的少数几个地方之一。

The idref element
The idref element is simply an error-proof way to pass the id (string value - not a reference) of another bean in the container to a or element.

idref 元素
idref 元素是一种简单的、提前错误的方式去传递id(字符串型)给另外的bean,可以用在
或者 元素中完成注入

<bean id="theTargetBean" class="..."/>

<bean id="theClientBean" class="...">
    <property name="targetName">
        <idref bean="theTargetBean"/>
    </property>
</bean>

The above bean definition snippet is exactly equivalent (at runtime) to the following snippet:

上面的bean定义片段与下列代码片段完全相同(在运行时):

<bean id="theTargetBean" class="..." />

<bean id="client" class="...">
    <property name="targetName" value="theTargetBean"/>
</bean>

The first form is preferable to the second, because using the idref tag allows the container to validate at deployment time that the referenced, named bean actually exists. In the second variation, no validation is performed on the value that is passed to the targetName property of the client bean. Typos are only discovered (with most likely fatal results) when the client bean is actually instantiated. If the client bean is a prototype bean, this typo and the resulting exception may only be discovered long after the container is deployed.

第一种形式优于第二种形式,因为使用idref标签允许容器在部署时验证所引用的、命名的bean实际上存在。在第二个变化中,没有对传递给客户bean的targetName属性的值执行验证。当客户端bean实际被实例化时,只会发现拼写错误(最有可能是致命的结果)。如果客户端bean是一个原型bean,那么这个输入错误和由此产生的异常可能只会在容器被部署很久之后才被发现。(idref 是传bean的字符串id的,可能这个会在容器初始化的时候会检查,而ref是bean实例化的时候没有才报错(有些bean配置了延迟实例化,即懒加载,只有在第一次getBean的时候才实例化),容器应该可以调节是否马上实例化配置文件中的bean吧-,-,反正还是用第二个,这个没什么人用的)

The local attribute on the idref element is no longer supported in the 4.0 beans xsd since it does not provide value over a regular bean reference anymore. Simply change your existing idref local references to idref bean when upgrading to the 4.0 schema.

idref元素上的local属性不再在4.0 bean xsd中得到支持,因为它不再为常规bean引用提供value。在升级到4.0模式时,只需将现有的idref local引用改为idref bean。

A common place (at least in versions earlier than Spring 2.0) where the element brings value is in the configuration of AOP interceptors in a ProxyFactoryBean bean definition. Using elements when you specify the interceptor names prevents you from misspelling an interceptor id.

一个常见的地方(至少在比Spring 2.0版本更早的版本中),在ProxyFactoryBean bean定义中, 元素带来的价值是在AOP拦截器的配置中。当您指定拦截器名称时,使用 元素可以防止您错误地拼写截取程序id。

References to other beans (collaborators)
The ref element is the final element inside a or definition element. Here you set the value of the specified property of a bean to be a reference to another bean (a collaborator) managed by the container. The referenced bean is a dependency of the bean whose property will be set, and it is initialized on demand as needed before the property is set. (If the collaborator is a singleton bean, it may be initialized already by the container.) All references are ultimately a reference to another object. Scoping and validation depend on whether you specify the id/name of the other object through the bean, local, or parent attributes.

引用其他bean(协作者)
ref元素是 或 定义元素中的最后一个元素。在这里,你将一个bean的指定属性的值设置为引用容器管理的另一个bean(一个合作者)的引用。被引用的bean是bean的属地,它的属性将被设置,并且在属性设置之前根据需要初始化它(如果合作者是一个单例bean,它可能已经被容器初始化了)。所有的引用最终都是对另一个对象的引用。确定范围和验证取决于您是否通过bean、local或parent 属性指定另一个物体的id/name。

Specifying the target bean through the bean attribute of the tag is the most general form, and allows creation of a reference to any bean in the same container or parent container, regardless of whether it is in the same XML file. The value of the bean attribute may be the same as the id attribute of the target bean, or as one of the values in the name attribute of the target bean.

通过 标签的bean属性指定目标bean,是最通用的形式,并且允许在同一个容器或其母容器中创建对任何bean的引用,不管它是否在同一个XML文件中。bean属性的值可能与目标bean的id属性相同,或者作为目标bean的name属性中的一个值。

<ref bean="someBean"/>

Specifying the target bean through the parent attribute creates a reference to a bean that is in a parent container of the current container. The value of the parent attribute may be the same as either the id attribute of the target bean, or one of the values in the name attribute of the target bean, and the target bean must be in a parent container of the current one. You use this bean reference variant mainly when you have a hierarchy of containers and you want to wrap an existing bean in a parent container with a proxy that will have the same name as the parent bean.

通过parent 属性指定目标bean,会创建一个父容器中的bean引用在当前容器中。parent 属性的值可能与目标bean的id属性相同,或者目标bean的name属性中的一个值,目标bean必须位于当前的父容器中。您可以使用这个bean引用变体,主要是当您有一个容器的层次结构时,您想要用一个与父bean同名的代理来包装一个现有的bean。(当前容器引用父容器的bean时需用使用代理类-,-)

<!-- in the parent context -->
<bean id="accountService" class="com.foo.SimpleAccountService">
    <!-- insert dependencies as required as here -->
</bean>
<!-- in the child (descendant) context -->
<bean id="accountService" <!-- bean name is the same as the parent bean -->
    class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="target">
        <ref parent="accountService"/> <!-- notice how we refer to the parent bean -->
    </property>
    <!-- insert other configuration and dependencies as required here -->
</bean>

The local attribute on the ref element is no longer supported in the 4.0 beans xsd since it does not provide value over a regular bean reference anymore. Simply change your existing ref local references to ref bean when upgrading to the 4.0 schema.

ref元素上的local 属性不再在4.0 bean xsd中得到支持,因为它不再为常规bean引用提供value。在升级到4.0模式时,只需将现有的ref local 引用更改为ref bean。

Inner beans
A element inside the or elements defines a so-called inner bean.

内部beans(仅仅不是平级的写法而已,不是使用内部类就得用这种写法的意思)
在 or 元素里面使用 也就是所谓的内部bean。

<bean id="outer" class="...">
    <!-- instead of using a reference to a target bean, simply define the target bean inline -->
    <property name="target">
        <bean class="com.example.Person"> <!-- this is the inner bean -->
            <property name="name" value="Fiona Apple"/>
            <property name="age" value="25"/>
        </bean>
    </property>
</bean>

An inner bean definition does not require a defined id or name; if specified, the container does not use such a value as an identifier. The container also ignores the scope flag on creation: Inner beans are always anonymous and they are always created with the outer bean. It is not possible to inject inner beans into collaborating beans other than into the enclosing bean or to access them independently.

内部bean定义不需要定义的id或name;如果指定的话,容器不会使用标识符这样的值。容器还忽略了scope flag:内bean总是匿名的,它们总是用外bean创建。不可能将内部bean注入到合作bean中,应该是将其放入封闭的bean中,或者独立地访问它们。

As a corner case, it is possible to receive destruction callbacks from a custom scope, e.g. for a request-scoped inner bean contained within a singleton bean: The creation of the inner bean instance will be tied to its containing bean, but destruction callbacks allow it to participate in the request scope’s lifecycle. This is not a common scenario; inner beans typically simply share their containing bean’s scope.

内部bean通常只是简单地共享它们的外部bean所包含bean的范围。而不应该破坏它。

Collections
In the , , , and elements, you set the properties and arguments of the Java Collection types List, Set, Map, and Properties, respectively.

集合
在, , 和 元素,你分别设置 List, Set, Map 或 Properties

<bean id="moreComplexObject" class="example.ComplexObject">
    <!-- results in a setAdminEmails(java.util.Properties) call -->
    <property name="adminEmails">
        <props>
            <prop key="administrator">[email protected]</prop>
            <prop key="support">[email protected]</prop>
            <prop key="development">[email protected]</prop>
        </props>
    </property>
    <!-- results in a setSomeList(java.util.List) call -->
    <property name="someList">
        <list>
            <value>a list element followed by a reference</value>
            <ref bean="myDataSource" />
        </list>
    </property>
    <!-- results in a setSomeMap(java.util.Map) call -->
    <property name="someMap">
        <map>
            <entry key="an entry" value="just some string"/>
            <entry key ="a ref" value-ref="myDataSource"/>
        </map>
    </property>
    <!-- results in a setSomeSet(java.util.Set) call -->
    <property name="someSet">
        <set>
            <value>just some string</value>
            <ref bean="myDataSource" />
        </set>
    </property>
</bean>

The value of a map key or value, or a set value, can also again be any of the following elements:

map的key或value,set的value可以使用以下元素:

bean | ref | idref | list | set | map | props | value | null

Collection merging
The Spring container also supports the merging of collections. An application developer can define a parent-style , , or element, and have child-style , , or elements inherit and override values from the parent collection. That is, the child collection’s values are the result of merging the elements of the parent and child collections, with the child’s collection elements overriding values specified in the parent collection.

集合合并
Spring容器还支持集合的合并。你可以先定义个父bean,然后再定义子bean是继承父bean的,然后在子bean中覆盖父bean的值

This section on merging discusses the parent-child bean mechanism. Readers unfamiliar with parent and child bean definitions may wish to read the relevant section before continuing.
The following example demonstrates collection merging:

关于合并的这一部分讨论了父子bean机制。不熟悉父和子bean的定义的读者可能希望在继续之前阅读相关部分。
下面的例子演示了集合合并:

<beans>
    <bean id="parent" abstract="true" class="example.ComplexObject">
        <property name="adminEmails">
            <props>
                <prop key="administrator">[email protected]</prop>
                <prop key="support">[email protected]</prop>
            </props>
        </property>
    </bean>
    <bean id="child" parent="parent">
        <property name="adminEmails">
            <!-- the merge is specified on the child collection definition -->
            <props merge="true">
                <prop key="sales">[email protected]</prop>
                <prop key="support">[email protected]</prop>
            </props>
        </property>
    </bean>
<beans>

Notice the use of the merge=true attribute on the element of the adminEmails property of the child bean definition. When the child bean is resolved and instantiated by the container, the resulting instance has an adminEmails Properties collection that contains the result of the merging of the child’s adminEmails collection with the parent’s adminEmails collection.

请注意,在子bean定义的adminemail属性的 元素上使用merge=true属性。当子bean被容器解析并实例化时,产生的实例有一个adminemail属性集合,它包含了将孩子的adminemail集合与父的adminemail集合合并的结果。

administrator=administrator@example.com
sales=sales@example.com
support=support@example.co.uk

The child Properties collection’s value set inherits all property elements from the parent , and the child’s value for the support value overrides the value in the parent collection.

儿童属性集合的值集继承父中的所有属性元素,并且孩子的支持值的值将覆盖父集合中的值。

This merging behavior applies similarly to the , , and collection types. In the specific case of the element, the semantics associated with the List collection type, that is, the notion of an ordered collection of values, is maintained; the parent’s values precede all of the child list’s values. In the case of the Map, Set, and Properties collection types, no ordering exists. Hence no ordering semantics are in effect for the collection types that underlie the associated Map, Set, and Properties implementation types that the container uses internally.

这种合并行为类似于 , , 和类型。在元素的情况下,与类型相关的语义,即有序集合的值的概念,保持不变;父类的值先于所有子列表的值(应该是指父的value优先add到list中)。在Map、Set和Properties托收类型的情况下,不存在排序。因此,对于容器在内部使用的关联映射、集合和属性实现类型的集合类型,没有排序语义。

Limitations of collection merging
You cannot merge different collection types (such as a Map and a List), and if you do attempt to do so an appropriate Exception is thrown. The merge attribute must be specified on the lower, inherited, child definition; specifying the merge attribute on a parent collection definition is redundant and will not result in the desired merging.

集合合并的限制
您不能合并不同的收集类型(例如Map和List),如果您尝试这样做,就会抛出一个适当的异常。合并属性必须在较低的、继承的、子定义上指定;在父托收定义中指定merge属性是多余的,不会导致期望的合并。

猜你喜欢

转载自blog.csdn.net/qq_42786889/article/details/82257568
今日推荐