依赖注入的详细配置

Dependencies and configuration in detail

直接代码


    
    
    
    
    



    




    
    
        
            jdbc.driver.className=com.mysql.jdbc.Driver
            jdbc.url=jdbc:mysql://localhost:3306/mydb
        
    




    
        
    




    


    
    

References to other beans (collaborators)

引用其他bean(collaborators)






    



    class="org.springframework.aop.framework.ProxyFactoryBean">
    
         
    
    


Inner beans

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



    
    
         
            
            
        
    


An inner bean definition does not require a defined id or name; the container ignores these values. It also ignores the scope flag. 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.

Collections

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



    
    
        
            [email protected]
            [email protected]
            [email protected]
        
    
    
    
        
            a list element followed by a reference
            
        
    
    
    
        
            
            
        
    
    
    
        
            just some string
            
        
    


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

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.

This section on merging discusses the parent-child bean mechanism. Readers unfamiliar with parent and child bean definitions may wish to read the relevant sectionbefore continuing.

The following example demonstrates collection merging:



    
        
            
                [email protected]
                [email protected]
            
        
    
    
        
            
            
                [email protected]
                [email protected]
            
        
    


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’sadminEmails collection.


[email protected]
[email protected]
[email protected]


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 theList 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, andProperties collection types, no ordering exists. Hence no ordering semantics are in effect for the collection types that underlie the associated Map, Set, and Propertiesimplementation types that the container uses internally.

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.

Strongly-typed collection

With the introduction of generic types in Java 5, you can use strongly typed collections. That is, it is possible to declare a Collection type such that it can only contain Stringelements (for example). If you are using Spring to dependency-inject a strongly-typed Collection into a bean, you can take advantage of Spring’s type-conversion support such that the elements of your strongly-typed Collection instances are converted to the appropriate type prior to being added to the Collection.

public class Foo {

    private Map accounts;

    public void setAccounts(Map accounts) {
        this.accounts = accounts;
    }
}

     id="foo" class="x.y.Foo">
         name="accounts">
            
                 key="one" value="9.99"/>
                 key="two" value="2.75"/>
                 key="six" value="3.99"/>
            
        
    

When the accounts property of the foo bean is prepared for injection, the generics information about the element type of the strongly-typed Map is available by reflection. Thus Spring’s type conversion infrastructure recognizes the various value elements as being of type Float, and the string values 9.99, 2.75, and 3.99 are converted into an actual Float type.

Null and empty string values

Spring treats empty arguments for properties and the like as empty Strings. The following XML-based configuration metadata snippet sets the email property to the emptyString value ("").

 class="ExampleBean">
     name="email" value=""/>

The preceding example is equivalent to the following Java code: exampleBean.setEmail(""). The  element handles null values. For example:

 class="ExampleBean">
     name="email">
        
    

The above configuration is equivalent to the following Java code: exampleBean.setEmail(null).

XML shortcut with the p-namespace

The p-namespace enables you to use the bean element’s attributes, instead of nested  elements, to describe your property values and/or collaborating beans.

Spring supports extensible configuration formats with namespaces, which are based on an XML Schema definition. The beans configuration format discussed in this chapter is defined in an XML Schema document. However, the p-namespace is not defined in an XSD file and exists only in the core of Spring.

The following example shows two XML snippets that resolve to the same result: The first uses standard XML format and the second uses the p-namespace.

 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">

     name="classic" class="com.example.ExampleBean">
         name="email" value="[email protected]"/>
    

     name="p-namespace" class="com.example.ExampleBean"
        p:email="[email protected]"/>

The example shows an attribute in the p-namespace called email in the bean definition. This tells Spring to include a property declaration. As previously mentioned, the p-namespace does not have a schema definition, so you can set the name of the attribute to the property name.

This next example includes two more bean definitions that both have a reference to another bean:

 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">

     name="john-classic" class="com.example.Person">
         name="name" value="John Doe"/>
         name="spouse" ref="jane"/>
    

     name="john-modern"
        class="com.example.Person"
        p:name="John Doe"
        p:spouse-ref="jane"/>

     name="jane" class="com.example.Person">
         name="name" value="Jane Doe"/>
    

As you can see, this example includes not only a property value using the p-namespace, but also uses a special format to declare property references. Whereas the first bean definition uses  to create a reference from bean john to bean jane, the second bean definition uses p:spouse-ref="jane" as an attribute to do the exact same thing. In this case spouse is the property name, whereas the -ref part indicates that this is not a straight value but rather a reference to another bean.

Note

The p-namespace is not as flexible as the standard XML format. For example, the format for declaring property references clashes with properties that end in Ref, whereas the standard XML format does not. We recommend that you choose your approach carefully and communicate this to your team members, to avoid producing XML documents that use all three approaches at the same time.

XML shortcut with the c-namespace

Similar to the the section called “XML shortcut with the p-namespace”, the c-namespace, newly introduced in Spring 3.1, allows usage of inlined attributes for configuring the constructor arguments rather then nested constructor-arg elements.

Let’s review the examples from the section called “Constructor-based dependency injection” with the c: namespace:

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

    "bar" class="x.y.Bar"/>
    "baz" class="x.y.Baz"/>

    
    "foo" class="x.y.Foo">
        "bar"/>
        "baz"/>
        "[email protected]"/>
    

    
    "foo" class="x.y.Foo" c:bar-ref="bar" c:baz-ref="baz" c:email="[email protected]"/>

The c: namespace uses the same conventions as the p: one (trailing -ref for bean references) for setting the constructor arguments by their names. And just as well, it needs to be declared even though it is not defined in an XSD schema (but it exists inside the Spring core).

For the rare cases where the constructor argument names are not available (usually if the bytecode was compiled without debugging information), one can use fallback to the argument indexes:

"foo" class="x.y.Foo" c:_0-ref="bar" c:_1-ref="baz"/>
Note

Due to the XML grammar, the index notation requires the presence of the leading _ as XML attribute names cannot start with a number (even though some IDE allow it).

In practice, the constructor resolution mechanism is quite efficient in matching arguments so unless one really needs to, we recommend using the name notation through-out your configuration.

Compound property names

You can use compound or nested property names when you set bean properties, as long as all components of the path except the final property name are not null. Consider the following bean definition.

 id="foo" class="foo.Bar">
     name="fred.bob.sammy" value="123" />

The foo bean has a fred property, which has a bob property, which has a sammy property, and that final sammy property is being set to the value 123. In order for this to work, thefred property of foo, and the bob property of fred must not be null after the bean is constructed, or a NullPointerException is thrown.

4.4.3 Using depends-on

If a bean is a dependency of another that usually means that one bean is set as a property of another. Typically you accomplish this with the  element in XML-based configuration metadata. However, sometimes dependencies between beans are less direct; for example, a static initializer in a class needs to be triggered, such as database driver registration. The depends-on attribute can explicitly force one or more beans to be initialized before the bean using this element is initialized. The following example uses the depends-on attribute to express a dependency on a single bean:

 id="beanOne" class="ExampleBean" depends-on="manager"/>
 id="manager" class="ManagerBean" />

To express a dependency on multiple beans, supply a list of bean names as the value of the depends-on attribute, with commas, whitespace and semicolons, used as valid delimiters:

 id="beanOne" class="ExampleBean" depends-on="manager,accountDao">
     name="manager" ref="manager" />


 id="manager" class="ManagerBean" />
 id="accountDao" class="x.y.jdbc.JdbcAccountDao" />
Note

The depends-on attribute in the bean definition can specify both an initialization time dependency and, in the case of singleton beans only, a corresponding destroy time dependency. Dependent beans that define a depends-on relationship with a given bean are destroyed first, prior to the given bean itself being destroyed. Thus depends-on can also control shutdown order.


你可能感兴趣的:(Spring)