Spring core technology (4)

Continued from the previous article: Spring core technology (3)

version 5.1.8.RELEASE

1.4.2 Dependency and configuration details

As mentioned in the previous section, you can define bean properties and constructor parameters as the reference to other managed beans (collaborators) Reference, or as a value defined inline. Spring’s XML-based configuration metadata supports the sub-elements and for this purpose.

Direct value (basic type, string, etc.)

The value attribute specifies an attribute or constructor parameter as a readable string. Spring’s conversion service is used to convert these values ​​from String to the actual types of attributes or parameters. The following example shows the various values ​​to be set:

     

Below The example uses the p namespace for more concise XML configuration:

 

The preceding XML is more concise. However, unless you use an IDE that supports automatic property completion when creating the bean definition (such as IntelliJ IDEA or Spring Tool Suite), you will find spelling errors at runtime rather than design time. It is strongly recommended to use such IDE help.

You can also configure the java.util.Properties instance, as shown below:

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

The Spring container uses the JavaBeans PropertyEditor mechanism Convert the text in the element to an instance of java.util.Properties. This is a great shortcut and one of the few places where the Spring team recommends nesting elements instead of value attributes.

idref element

idref element is just a way to prevent The id attribute (string value-not reference) of a bean is passed to the or element. The following example shows how to use it:

   

The preceding bean definition code snippet is exactly equivalent to the following code snippet (runtime) :

 

The first form is better than the second form, because the use of the idref tag allows the container to verify the referenced during deployment Whether the named bean exists. In the second variant, no validation is performed on the value passed to the client bean targetName property. Spelling errors are only found when the client bean is actually instantiated (most likely a fatal result). If the client bean is a prototype bean, it may take a long time to discover this error and the resulting exception after the container is deployed.

4.0 beans XSD no longer supports the local attribute of the idref element, because it no longer provides other than regular bean Value other than reference. When upgrading to version 4.0, you need to change the existing idref local reference to idref bean.

One of the common places (at least earlier than Spring 2.0), the value of the element is the ProxyFactoryBean bean definition The configuration items of the AOP interceptor. Use the element when specifying the interceptor name to prevent misspelled interceptor IDs.

quoting other Bean (collaborator)

ref The element is or defines the final element inside the element. Here, you set the value of the bean specified property as a reference to another bean (collaborator) managed by the container. The referenced bean is a dependency of the bean whose property is to be set, and it is initialized as needed before setting the property. (If the collaborator is a singleton bean, it may have been initialized by the container.) All references are ultimately references to another object. The scope and validity depend on whether the ID or name of another object is specified through the bean, local, or parent attribute.

Specifying the target bean through the bean attribute of the tag is the most common way to allow creation of any object in the same container or parent container. A reference to the bean, whether it is in the same XML file or not. The value of the bean attribute can be the same as the id attribute of the target bean, or it can be the same as one of the name attributes of the target bean. The following example shows how to use the ref element:

via parent attribute specifying the target bean will create a reference to the bean in the parent container of the current container. The value of the parent attribute can be the same as the id attribute of the target bean, or it can be the same as one of the name attributes of the target bean. The target bean must be in the parent container of the current bean. When the container has a hierarchical structure and wants to wrap the existing beans in the parent container in the same way as the parent bean, the bean reference variable should be used mainly. The following pair of lists demonstrate how to use the parent attribute:

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

4.0 beans XSD no longer supports the local attribute of the ref element because it no longer provides values ​​other than regular bean references. When upgrading to the 4.0 architecture, you need to change the existing ref local reference to ref bean.

internal Bean

or element in the code> element defines an inner bean, as shown in the following example:

    < !-- this is the inner bean -->    

Internal bean definition does not need to define ID or name. Even if specified, the container does not use it as an identifier. The container also ignores the scope flag when it is created, because the inner bean is always anonymous and is always created with the outer bean. Inner beans cannot be individually accessed or injected into cooperative beans.

As an extreme case, you can receive a destruction callback from a custom scope, such as an inner bean whose scope is request contained in a singleton bean. The creation of an internal bean instance is associated with the bean that contains it, but the destruction callback allows it to participate in the life cycle of the request scope. This is not a common situation. Inner beans usually just share the scope of the bean that contains it.

collection

, ,

and elements are set Java Collection type List, Set, Map and Properties. The following example demonstrates how to use them:

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

The key or value of the map, or the value of the set, you can Is any of the following elements:

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

Set merge

< p>Spring container supports merged collections. Application developers can define the parent ,

, or element and define sub-elements ,

, or inherits and overrides the value of the parent collection. In other words, the elements of the sub-collection will overwrite the value specified in the parent collection, and the value of the sub-collection is the result of merging the elements of the parent collection and the sub-collection.

This section on merging discusses the parent-child bean mechanism. Readers who are not familiar with parent-child bean definitions may wish to read the relevant sections before reading on.

The following example demonstrates collection merging:

  < property name="adminEmails">  [email protected] [email protected]        < prop key="sales">[email protected] [email protected]   

Pay attention to the element of the merge=true attribute of the adminEmails attribute in the child bean definition use. When the container parses and instantiates the child bean, the generated instance has a adminEmails Properties collection, which contains the sub-collection adminEmails< /code> The result of merging with the parent adminEmails collection. The following list shows the result:

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

Properties The value of the collection inherits all the attribute elements of the parent element , and the value of support in the child element will override the value of the parent collection.

This merging behavior also applies to the ,

and collections Types of. In the specific scenarios of the element, it is recommended to maintain the semantics associated with the List collection type (that is, the concept of an ordered collection). The value of the parent precedes the value of all child lists. In the Map, Set and Properties collection type scenarios, there is no order. Therefore, the Map, Set, and Properties implementation classes used inside the container are also out of order.

Limitations of collection merging

You cannot merge different collection types (such as Map and List). If you try to do this, the corresponding Exception will be thrown. The merge attribute must be specified on the lower-level sub-definition. Specifying the merge attribute on the parent collection definition is redundant and will not cause the desired merge.

Strongly typed collections

With the generic types introduced in Java 5, you can use strongly typed collections. In other words, you can declare a type of Collection so that it can only contain (for example) String elements. If you use Spring to inject the strongly typed Collection dependency into the bean, you can use Spring's type conversion support so that the elements of the strongly typed Collection instance are added to the Collection< /code> before converting to the appropriate type. The following Java class and bean definitions demonstrate how to do this:

public class SomeClass {private Map accounts; public void setAccounts(Map accounts) {this.accounts = accounts; }}
    < entry key="one" value="9.99"/>     < /bean>

When the accounts attribute of the something bean is ready to be injected, the strongly typed element can be obtained through reflection Generic information of >Map. Therefore, Spring’s type conversion mechanism recognizes various values ​​as Float types, and converts string values ​​(9.99, 2.75 and 3.99) converted to actual Float type.

null and empty string

Spring treats empty parameters such as attributes as empty strings. The following XML-based configuration metadata snippet sets the email attribute to an empty string ("").

 

The above example is equivalent to The following Java code:

exampleBean.setEmail("");

The element can handle null< /code> value. An example is shown below:

   

The above configuration is equivalent to the following Java code:

exampleBean.setEmail(null);

XML shortcut with p namespace< /strong>

The p namespace allows you to use the attributes of the bean element (instead of nested elements) to describe the attribute value or Collaborative bean.

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

The following example shows two XML fragments (the first using the standard XML format and the second using the p namespace) parsed into the same result:

     

This example demonstrates the setting of the email attribute of the p namespace called in the bean definition. This tells Spring to include a property declaration. As mentioned before, the p namespace has no schema definition, so the name of the attribute can be set to the attribute name.

The next example includes two other bean definitions, both of which reference another bean:

        

This example not only includes attribute values ​​using the p namespace, but also uses a special format to declare attribute references. The first bean definition uses to create a reference from bean john to bean jane , And the second bean definition uses p:spouse-ref="jane" as an attribute to perform exactly the same operation. In this case, spouse is the attribute name, and the -ref part means that this is not a direct value, but a reference to another bean.

The p namespace is not as flexible as the standard XML format. For example, the format of declaring attribute references conflicts with the attributes ending in Ref, while the standard XML format does not. We recommend choosing your method carefully and communicating it to other team members to avoid generating XML documents that use all three methods at the same time.

XML shortcut with c namespace

Similar to XML shortcut with p namespace, introduced in Spring 3.1 The c namespace allows the use of inline attributes to configure constructor parameters instead of nesting constructor-arg elements.

The following example uses the c: namespace to perform the same operations as constructor-based dependency injection:

          

When the constructor parameter is set by name,< The code>c: namespace and p: use the same convention (bean reference at the trailing -ref). Similarly, it needs to be declared in the XML file, even if it is not defined in the XSD schema (it exists inside the Spring core).

For the rare case where the constructor parameter name is not available (usually compiling bytecode without debugging information), you can use alternate parameter indexes, as shown below:

Because XML syntax is used, and the XML attribute name cannot start with a number (even if some IDEs allow it), the index notation requires a prefix _. The element can also use the corresponding index symbol, but it is not commonly used because the order of declaration is usually sufficient.

Actually, the constructor resolution mechanism is very effective when matching parameters, so unless you really need it, we recommend using name notation throughout the configuration.

Composite attribute name

When setting bean attributes, you can use composite or nested attribute names, as long as all components of the path except the final attribute name None of them are null. Please see the bean definition below:

 

something bean has a fred attribute, and the fred attribute contains bob Attribute, the bob attribute contains the sammy attribute, and finally the value of the sammy attribute is set to 123. To ensure that it can run normally, after constructing the bean, the fred attribute of something and the bob attribute of the fred attribute Must not be null. Otherwise, a NullPointerException will be thrown.

1.4.3 Using depends-on

If a bean is a dependency of another bean, usually Means to set a bean as a property of another bean. Normally, you can use the element in the XML-based configuration metadata to accomplish this. However, sometimes the dependencies between beans are not so straightforward. For example, static initializers that need to be triggered in the class, such as database driver registration. The depends-on attribute can explicitly force the initialization of one or more beans before initializing the beans that use this element. The following example uses the depends-on attribute to indicate the dependency on a single bean:

To indicate dependencies on multiple beans, please provide a list of bean names as depends-on The value of the attribute (comma, space and semicolon are valid separators):

 

The depends-on attribute can specify the dependency at initialization, or the dependency at the time of singleton bean destruction. The dependencies defined by depends-on will be destroyed before the specified bean itself is destroyed. In this way, depends-on can also control the stopping sequence.

1.4.4 Delayed-initialized Bean

By default, the ApplicationContext implementation will be initialized All singleton beans are created and configured as part of the initialization process. Usually, this kind of pre-instancing is reasonable, because errors in the configuration or environment can be found immediately, rather than hours or even days later. When this is not desired, you can prevent the pre-instancing of singleton beans by marking the bean definition as lazy initialization. Lazily initialized beans tell the IoC container to create bean instances on the first request, not at startup.

In XML, this behavior is controlled by the lazy-init attribute of the element, as shown in the following example:

When the current configuration is used by ApplicationContext, lazy bean will not be instantiated in advance when ApplicationContext is started The not.lazy bean will be instantiated in advance.

But when the delayed-initialized bean is a dependency of a singleton bean that has not been delayed-initialized, ApplicationContext will create a delayed-initialized bean, because it must satisfy the dependency of the singleton. Lazy-initialized bean will be injected into other singleton beans that are not lazy-initialized.

You can also use the default-lazy-init attribute on the element to control the container-level lazy initialization, as follows The example shows:

  pre> 

  • My CSDN: https://blog.csdn.net/liweitao7610
  • My blog garden: https://www.cnblogs.com/aotian/
  • My short book: https://www.jianshu.com/u/6b6e162f1fdc

Leave a Comment

Your email address will not be published.