Spring series dependency injection method "suggestions collection"

1, Dependency injection mode

For spring When configuring a bean, if you need to provide some initialization parameters for the bean, you need to use the dependency injection method. The so-called dependency injection is the process of passing some parameters required by the bean to the bean instance object through spring. There are three methods of dependency injection in spring:

·Use the setter method of attribute injection, which is the most commonly used method; ·Injection using a constructor; ·Use Filed injection (for annotation mode).

1. Use attribute injection

Attribute injection is to inject the attribute value or dependent object of the Bean through the setXxx() method. Because the attribute injection method has the advantages of selectivity and high flexibility, attribute injection is the most commonly used injection method in practical applications.

<bean id="......" class="......">  
    <property name=""Property 1" value="......"/>  
    <property name=""Property 2" value="......"/>  
    ......  
</bean>  

Attribute injection requires Bean to provide a default constructor and provide the corresponding Setter method for the attribute to be injected. Spring first calls the Bean's default constructor to instantiate the Bean object, and then calls the Setter method to inject attribute values through reflection. Let's take a simple example.

This code is by Java Architect must see network-Structure Sorting
package com.spring.model;

public class Car {
    
    private int maxSpeed;
    private String brand;
    private double price;
    
    public int getMaxSpeed() {
        return maxSpeed;
    }
    //Be sure to write the set method of the injected object
    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }
    public String getBrand() {
        return brand;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    
    public void run(){
        System.out.println("brand:"+brand+",maxSpeed:"+maxSpeed+",price:"+price);
    }
}

Car class defines three attributes and provides corresponding Setter methods. (Note: the default constructor is a constructor without parameters. The Java language stipulates that if there is no constructor defined in the class, the JVM will automatically generate a default constructor for it. On the contrary, if the constructor is displayed and defined in the class, the JVM will not generate a default constructor for it. Therefore, it is assumed that a constructor with parameters is displayed and defined in the car class, such as public ca R (string brand), you need to provide a default constructor public Car(), otherwise an exception will be thrown when using attribute injection.) Next, inject attributes into Car in Spring configuration file:

<!-- Attribute injection -->
<bean id="car" class="com.spring.model.Car">  
    <property name="maxSpeed" value="200"></property>
    <property name="brand" value="red flag CA72"></property>  
    <property name="price" value="200000.00"></property>
</bean>

In the above code, a Bean is configured and attribute values are provided for the three attributes of the Bean. Specifically, each attribute of the Bean corresponds to a < property > tag. Name is the name of the attribute. The Bean implementation class has its corresponding Setter method: maxSpeed corresponds to setMaxSpeed(), brand corresponds to setBrand(). It should be pointed out that Spring only checks whether there is a corresponding Setter method in the Bean, and does not require whether there is a corresponding attribute variable in the Bean. For example, the property configuration item of < property name = "brand" / > in the configuration file only requires the setBrand() method in the Car class, but the Car class does not have to have the brand member variable.

Test method:

This code is by Java Architect must see network-Structure Sorting
/**
 * Attribute injection
 */
@Test
public void test(){
    //Read configuration file
    ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
    //Get an instance of the bean
    Car car=(Car) ctx.getBean("car");
    car.run();
}

 2. Constructor Inject

Constructor injection is another common injection method besides attribute injection. It ensures that some necessary attributes are set when the Bean is instantiated, and ensures that the Bean instance can be used after instantiation. Usage: First, in the class, you do not need to set the setter method for the property, but you need to generate the constructor with parameters of the class. Second, configure the bean s of this class in the configuration file and configure the constructor. The < constructor Arg > node is used in the configuration constructor, which has four attributes: ·Index is the index, specifying the injected attribute, starting from 0; ·Type refers to the type corresponding to the attribute; ·ref refers to the referenced dependent object; ·Value when the injected object is not a dependent object but a basic data type, use value;

(1) Match input parameters by type

If any available Car object must provide the values of maxSpeed, brand and price, attribute injection can only provide guarantee artificially during configuration, but not at the syntax level. At this time, constructor injection can well meet this requirement. The premise of using constructor injection is that Bean must provide a constructor with parameters. Below, Car is provided with a constructor that can set maxSpeed, brand and price attributes.

package com.spring.model;

public class Car {
    
    private int maxSpeed;
    private String brand;
    private double price;
    
    //Structural method with parameters
    public Car(int maxSpeed,String brand, double price){
        this.maxSpeed=maxSpeed;
        this.brand=brand;
        this.price=price;
    }
    
    public void run(){
        System.out.println("brand:"+brand+",maxSpeed:"+maxSpeed+",price:"+price);
    }
}

The configuration method of constructor injection is different from that of attribute injection. Use constructor injection to assemble the Car Bean in the spring configuration file.

<!-- Constructor Inject (Match by type) -->
<bean id="car1" class="com.spring.model.Car">  
    <constructor-arg type="int" value="300"></constructor-arg>
    <constructor-arg type="java.lang.String" value="bmw"></constructor-arg>
    <constructor-arg type="double" value="300000.00"></constructor-arg>
</bean>

There is a type attribute in the < constructor Arg > element, which represents the type of parameters in the constructor and provides spring with "information" to judge the correspondence between configuration items and constructor input parameters.

(2) Match input parameters by index

We know that the Java language distinguishes different overloaded methods by the type and order of input parameters. For the Car class in the above code, Spring can know that "BMW" corresponds to the brand input of String type and "300000.00" corresponds to the price input of double type only through the parameter type specified by the type attribute. However, if the three input parameters of the Car constructor have the same type, the corresponding relationship cannot be determined only by type. At this time, it needs to be determined by the input parameter index. In order to better demonstrate the configuration of matching input parameters by index, the Car constructor is specially adjusted.

public Car(String brand, String corp,double price){
    this.brand=brand;
    this.corp=corp;
    this.price=price;
}

The input parameter types of brand and corp are both String, so String cannot determine whether < constructor Arg > with type String corresponds to brand or corp. However, this uncertainty can be eliminated by displaying the index of the specified parameter, as shown below.

<!-- Constructor Inject (Match by index) -->
<bean id="car2" class="com.spring.model.Car"> 
    <!-- Note that the index starts at 0 --> 
    <constructor-arg index="0" value="bmw"></constructor-arg>
    <constructor-arg index="1" value="China FAW"></constructor-arg>
    <constructor-arg index="2" value="300000.00"></constructor-arg>
</bean>

The first parameter index of the constructor is 0, the second is 1, and so on. Therefore, it is easy to know that "BMW" corresponds to brand input parameter, while "China FAW" corresponds to corp input parameter.

(3) Joint use of type and index to match input parameters Sometimes you need to use type and index together to determine the correspondence between the matching item and the constructor input parameter. See the following code.

public Car(String brand, String corp,double price){
    this.brand=brand;
    this.corp=corp;
    this.price=price;
}

public Car(String brand, String corp,int maxSpeed){
    this.brand=brand;
    this.corp=corp;
    this.maxSpeed=maxSpeed;
}

Here, Car has two overloaded constructors, both of which have three input parameters. In view of this situation, it is difficult to meet the requirements according to the configuration of the input parameter index. At this time, you need to use the < constructor Arg > type and index together to solve the problem. See the following code.

<!-- Constructor Inject (The corresponding relationship is determined by the input parameter type and location index) -->
<!-- corresponding public Car(String brand, String corp,int maxSpeed)Constructor -->
<bean id="car3" class="com.spring.model.Car">  
    <constructor-arg index="0" type="java.lang.String" value="Benz"></constructor-arg>
    <constructor-arg index="1" type="java.lang.String" value="China FAW"></constructor-arg>
    <constructor-arg index="2" type="int" value="200"></constructor-arg>
</bean>

For the above two constructors, if they are configured only through index, Spring will not be able to determine whether the configuration item of the third input parameter corresponds to the maxSpeed of int or the price of double. When index matching is adopted, the real ambiguity lies in the third input parameter. Therefore, it is only necessary to specify the type of the third input parameter. Therefore, in the above code, the type attribute of the first and second < constructor Arg > elements can be removed. For the potential configuration ambiguity caused by the same number of parameters but different types, the Spring container can start correctly without giving error information. It will randomly instantiate the Bean with a matching constructor, and the selected constructor may not be what the user wants. Therefore, special care must be taken to avoid potential errors.

 3. Use field (file) injection (for annotation mode)

In addition to the above-mentioned setter method using attributes or constructor method to inject dependent objects, there is another method to inject dependent objects, that is, using annotations.

Let's look at an example. First, we don't use annotations.

Create a new business interface:

package com.spring.service;

public interface ICommonService {
    
    public void add();
}

Implementation class:

package com.spring.service.impl;

import com.spring.dao.ICommonDao;
import com.spring.service.ICommonService;

public class CommonServiceImpl implements ICommonService{
    
    private ICommonDao commonDao;
    
    // The setter method required for dependency injection into DAO components
    public void setCommonDao(ICommonDao commonDao) {
        this.commonDao = commonDao;
    }
    
    public void add(){
        commonDao.add();
    }
}

dao layer interface:

package com.spring.dao;

public interface ICommonDao {
    public void add();
}

Implementation class:

package com.spring.dao.impl;

import com.spring.dao.ICommonDao;

public class CommonDaoImpl implements ICommonDao{
    
    public void add(){
        System.out.println("enter add!");
    }
}

Profile:

<bean id="commonDao" class="com.spring.dao.impl.CommonDaoImpl"></bean>
<bean id="commonService" class="com.spring.service.impl.CommonServiceImpl">
    <!-- Inject the required for persistent access DAO assembly -->
    <property name="commonDao" ref="commonDao"/>
</bean>

The above is how to inject dependent objects without annotations (using attribute injection). Let's take a look at using annotations to inject dependent objects for a bean.

(1) First, in the Spring container's configuration file ApplicationContext The following information is configured in the XML file, which is the template of a Spring configuration file

<?xml version="1.0" encoding="UTF-8"?>
<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"
    xmlns:context="http://www.springframework.org/schema/context"     xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd     ">
    
</beans>

Note: only the lines configured with purple part can introduce the annotation namespace, otherwise an error will be reported. The above configuration implicitly registers multiple processors for parsing annotations: AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor, PersistenceAnnotationBeanPostProcessor, etc.

(2) Secondly, open the < context: annotation config > node in the configuration file and tell the Spring container that dependent objects can be injected by annotation; Its code in the configuration file is as follows:

<beans>

......

<context:annotation-config></context:annotation-config>

......

</beans>

(3) Third, configure the bean object in the configuration file, as follows:

<bean id="commonDao" class="com.spring.dao.impl.CommonDaoImpl"></bean>
<bean id="commonService" class="com.spring.service.impl.CommonServiceImpl"></bean>

(4) Fourth, in the class that needs dependency injection (CommonServiceImpl in this case), declare a dependency object without generating the setter method of the dependency object, and add annotations to the object.

Modify the business layer implementation class CommonServiceImpl

package com.spring.service.impl; import javax.annotation.Resource; import com.spring.dao.ICommonDao; import com.spring.service.ICommonService; public class CommonServiceImpl implements ICommonService{ @Resource(name="commonDao") private ICommonDao commonDao; // //setter methods required for dependency injection into DAO components / / public void setcommondao (icommondao commondao) {/ / this.commondao = commondao; / /} public void add() {commondao. Add();}}

Among them, @ Autowired or @ Resource annotation can be used for Spring dependency injection in Java code. The difference between the two is: @ Autowired assembles by type by default and @ Resource assembles by name by default. Only when no bean matching the name is found will it be assembled by type.

For example, @ Autowired is used to annotate the instance object of ICommonDao interface in the above code. It will go to the Spring container to find the type matching the ICommonDao object. If the type is found, it will be injected into the commonDao field;

If @ Resource is used for dependency injection, it will first find the type matching the name in the Spring container according to the specified name attribute, for example: @ Resource(name="commonDao"). If the name is not found, it will find it according to the type. After finding it, it will inject the field commonDao.

Using annotations to inject dependent objects eliminates the need to write the setter method of dependent objects or the construction method of this class in the code, and eliminates the need to configure a large number of dependent objects in the configuration file, making the code more concise, clear and easy to maintain.

In the actual development of Spring IOC programming, it is recommended to use annotation for dependency injection.

2, Dependency injection - automatic assembly

In applications, we often use the < ref > tag to inject dependent objects into JavaBeans. At the same time, Spring provides us with an automatic assembly mechanism. When defining beans, the < Bean > tag has an autowire attribute, which we can specify to make the container automatically inject dependent objects into managed JavaBeans.

Automatic assembly is implemented in the configuration file, as follows: < bean id = "* * *" class = "* * *" autowire = "bytype" >

You only need to configure an autowire property to complete the automatic assembly. You don't need to write < property > in the configuration file, but you still need to generate the setter method of the dependent object in the class.

The autowire attribute of < bean > has the following six values. Their descriptions are as follows

1.No: automatic assembly is not enabled. Autowire defaults. By default, bean s need to be assembled through "ref", as follows:

package com.lei.common;
 
public class Customer 
{
    private Person person;
 
    public Customer(Person person) {
        this.person = person;
    }
 
    public void setPerson(Person person) {
        this.person = person;
    }
    //...
}
package com.lei.common;
 
public class Person 
{
    //...
}

Profile:

<bean id="customer" class="com.lei.common.Customer">
    <property name="person" ref="person" />
</bean>
<bean id="person" class="com.lei.common.Person" />

2.byName: by name} you can query the bean with the same name as the attribute in the container according to the name of the attribute. If it is not found, the attribute value is null. Suppose the Boss class has an attribute named car. If there happens to be a bean named car in the container, Spring will automatically assemble it to the Boss's car attribute.

Assemble beans according to the name of the Property. In this case, when the Customer sets autowire="byName", Spring will automatically find beans with the same Property name "person". After finding them, it will inject them into the Property by calling setPerson(Person person).

<bean id="customer" class="com.lei.common.Customer" autowire="byName" />
<bean id="person" class="com.lei.common.Person" />

If the corresponding bean configuration cannot be found according to the Property name, it is as follows:

<bean id="customer" class="com.lei.common.Customer" autowire="byName" />
<bean id="person_another" class="com.lei.common.Person" />

The Property name in the Customer is person, but the person cannot be found in the configuration file, only person_ Otherwise, the assembly will fail. After running, person=null in Customer.

3.byType: assemble by type} you can find beans matching this type in the container according to the attribute type. If there are multiple beans, an exception will be thrown. If not found, the attribute value will be null. Suppose there is a Car type attribute in the Boss class. If there is just a bean of Car type in the container, Spring will automatically assemble it to this attribute of the Boss.

Automatically assemble according to the data type of the Property. In this case, when the Customer sets autowire="byType", Spring will always look for bean s with the same Property type. After finding them, inject them by calling setPerson(Person person).

<bean id="customer" class="com.lei.common.Customer" autowire="byType" />
<bean id="person" class="com.lei.common.Person" />

What happens if there are two bean s of the same type in the configuration file? As follows:

<bean id="customer" class="com.lei.common.Customer" autowire="byType" />
<bean id="person" class="com.lei.common.Person" />
<bean id="person_another" class="com.lei.common.Person" />

Once configured as above, if two bean s with the same data type are configured, an unsatisfied dependencyexception will be thrown, as shown below: Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Therefore, once you have selected the "byType" type of automatic assembly, please make sure that each data type in your configuration file defines a unique bean.

4.constructor: similar to byType, the difference is that it applies to constructor parameters. If a bean with the same type as the constructor parameter is not found in the container, an exception will be thrown. (the byType mode is automatically assembled according to the data type of the constructor parameter.)

In this case, Spring will find a bean with the same parameter data type and inject it through the constructor public Customer(Person person).

<bean id="customer" class="com.lei.common.Customer" autowire="constructor" />
<bean id="person" class="com.lei.common.Person" />

5.autodetect: decide whether to use constructor or byType for automatic assembly through the introspection mechanism of bean class. If the bean has an empty constructor, the "byType" automatic assembly method will be adopted. Otherwise, the "constructor" automatic assembly method will be used.

In this case, Spring will first look for whether there is a default constructor in the Customer. If there is a case equivalent to the "constructor" above, inject it with the constructor. Otherwise, inject it in the way of "byType". Therefore, in this example, inject it by calling public Customer(Person person).

<bean id="customer" class="com.lei.common.Customer" autowire="autodetect" />
<bean id="person" class="com.lei.common.Person" />

6.default: determined by the default autowire attribute of the parent label < beans >.

Note: when configuring beans, the Autowire attribute in the < bean > tag takes precedence over its parent tag, that is, if the default Autowire attribute is defined as byName in the parent tag and byType in < bean >, the Spring IoC container will give priority to the configuration of the < bean > tag.

Summary: using automatic assembly, the configuration file is much simpler. However, automatic assembly is not perfect. Whether we use byName or byType, Spring may not be able to find the objects that JavaBeans depend on. In this case, you must abide by the naming specification of Java beans. In addition, if you use automatic assembly, the readability of Spring configuration files will be greatly reduced. We can't easily see the dependencies between beans, which also reduces the maintainability of the program to a certain extent; It is also easy to cause potential errors. For example, assemble by byName. If the attribute name is changed, Spring will not automatically assemble it to the attribute of bean.

Therefore, when using automatic assembly, we should weigh the advantages and disadvantages, reasonably combine it with ref method, try to reduce the workload and ensure the maintainability of the application. However, spring's reference does not recommend using this function in the definition.

Not all types can be automatically assembled. Data types that cannot be automatically assembled include Object, basic data types (Date, CharSequence, Number, URI, URL, Class, int), etc.

3, Detailed explanation of injection parameters

·Injection constant

Injection constants are the simplest of dependency injection. The configuration method is as follows:

<property name="message" value="Hello World!"/>
or
<property name="index"><value>1</value></property>

The above two methods are OK. From the perspective of configuration, the first one is more concise. Note that all specified in "value" here are strings. The Spring container converts this string to the type required by the attribute. If the conversion is wrong, the corresponding exception will be thrown.

·Injection set type

Java. The collection class in util package is the most commonly used data structure type, mainly including List, Set, Map and Properties. Spring provides special configuration element labels for these collection type Properties.

1.List: you need to use the < list > tag to configure injection.

Create a new Boss class and add a favorites attribute of List type to the class.

package com.spring.model;

import java.util.List;

public class Boss {
    
    private List favorites;

    public List getFavorites() {
        return favorites;
    }

    public void setFavorites(List favorites) {
        this.favorites = favorites;
    }
    
    public void print(){
        System.out.println(favorites);
    }
}

The corresponding configuration fragments in Spring are as follows:

<!-- injection List Type properties -->
<bean id="boss" class="com.spring.model.Boss">  
    <property name="favorites">
        <list>
            <value>Read the newspaper</value>
            <value>racing</value>
            <value>golf</value>
        </list>
    </property>
</bean>

The List attribute can inject strings through < value > or other beans in the container through < ref >.

2.Set: the < set > tag needs to be used to configure injection. Its configuration parameters and meanings are exactly the same as those of the < LSIT > tag. Specific configuration examples are as follows:

<bean id="......" class="......">
    <property name="......">
        <set>  
            <value>value1</value>  
            <value>value2</value>  
            ......  
        </set>
    </property>
</bean> 

3.Map: the < Map > tag needs to be used to configure injection, and its attributes "key type" and "value type" specify the data types of "key" and "value" respectively.

Add a jobs attribute of Map type in the Boss class.

package com.spring.model;

import java.util.List;
import java.util.Map;

public class Boss {

    private Map jobs;
    
    public Map getJobs() {
        return jobs;
    }

    public void setJobs(Map jobs) {
        this.jobs = jobs;
    }

    public void print1(){
        System.out.println(jobs);
    }
}

In the configuration file, you can provide configuration values for the jobs property in the following ways.

<!-- injection Map Type properties -->
<bean id="boss1" class="com.spring.model.Boss">  
    <property name="jobs">
        <map>
            <entry key="AM" value="Meet customers" />
            <entry key="PM" value="Internal meetings of the company" />
        </map>
    </property>
</bean> 

Where < Map > represents map injection, < entry > represents key value pair, < key > represents key data, < value > represents value data corresponding to key.

4.Properties: the < props > tag needs to be used to configure injection. The key and value types must be String and cannot be changed. The sub tag < prop key = "key" > value < / prop > specifies the key value pair.

The Properties type can actually be regarded as a special case of the Map type. The key and value of the Map element can be any type of object, while the key and value of the Properties property can only be a string. Add a Properties type mail property for the Boss.

package com.spring.model;

import java.util.List;
import java.util.Map;
import java.util.Properties;

public class Boss {
    
    private Properties mails;
    
    public Properties getMails() {
        return mails;
    }

    public void setMails(Properties mails) {
        this.mails = mails;
    }
    
    public void print2(){
        System.out.println(mails);
    }
}

The following configuration fragment provides configuration for mail.

<!-- injection Properties Type properties -->
<bean id="boss2" class="com.spring.model.Boss">  
    <property name="mails">
        <props>
            <prop key="jobMail">john-office@163.com</prop>
            <prop key="lifeMail">john-life@163.com</prop>
        </props>
    </property>
</bean>

Because the Properties key value pair can only be a string, its configuration is simpler than that of Map. Note that there is no < value > sub element label in the configuration.

·Reference other beans

The IOC roles defined in the "spring Bean" container can act as the matchmaker of each other. Next, add a Car type attribute to the Boss class.

package com.spring.model;

import java.util.List;
import java.util.Map;
import java.util.Properties;

public class Boss {
    
    private Car car;
    //Set car attribute
    public void setCar(Car car) {
        this.car = car;
    }

    public void print3(){
        System.out.println(car.getBrand()+"----"+car.getPrice()+"----"+car.getMaxSpeed());
    }
}

The boss Bean references the car Bean through the < ref > element to establish the boss's dependence on the car.

<bean id="car" class="com.spring.model.Car">  
    <property name="maxSpeed" value="200"></property>
    <property name="brand" value="red flag CA72"></property>  
    <property name="price" value="200000.00"></property>
</bean>
<!-- adopt ref Element reference bean -->
<bean id="boss3" class="com.spring.model.Boss">  
    <property name="car">
        <!--Reference the above defined car Bean-->
        <ref bean="car"></ref>
    </property>
</bean>

The < ref > element can reference other beans in the container through the following three attributes. ·Bean: this attribute allows you to refer to beans of the same container or parent container, which is the most common form.

·local: only beans defined in the same configuration file can be referenced through this attribute. It can use the XML parser to automatically check the legitimacy of the reference, so that the configuration errors can be found and corrected in time when developing and writing the configuration.

·Parent: refers to the Bean in the parent container. For example, the configuration of < ref parent = "car" > indicates that the Bean of car is the Bean in the parent container.

To illustrate the child container's reference to the Bean in the parent container, let's take a specific example. Suppose you have two configuration files, beans1 XML and beans2 XML, where beans1 XML is loaded by the parent container, and its configuration is as follows.

<?xml version="1.0" encoding="UTF-8"?>
<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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    ">
    
    <!--Defined in parent container car -->
    <bean id="car" class="com.spring.model.Car">
        <property name="brand" value="red flag CA72"></property> 
        <property name="maxSpeed" value="200"></property> 
        <property name="price" value="200000.00"></property>
    </bean>
    
</beans>

And beans2 XML is loaded by the sub container, and its configuration content is as follows.

<?xml version="1.0" encoding="UTF-8"?>
<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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    ">
    
    <!--1.Should Bean And in the parent container car Bean Have the same id -->
    <bean id="car" class="com.spring.model.Car">  
        <property name="brand" value="auspicious CT5"></property>  
        <property name="maxSpeed" value="100"></property>
        <property name="price" value="100000.00"></property>
    </bean>
    <bean id="boss" class="com.spring.model.Boss">  
        <property name="car">
            <!--Reference the in the parent container car,Not defined in 1 place Bean,If used<ref bean="car" />The at 1 of this container will be referenced car  -->
            <ref parent="car"></ref>
        </property>
    </bean>
</beans>

In beans1 A car Bean is configured in beans2.xml A car Bean is also configured in XML. Load beans1 through parent and child containers respectively XML and beans2 xml,beans2. The boss in XML refers to the car in the parent container through < ref parent = "car" >. The following is to load beans1 XML and beans2 The code of the XML configuration file.

/**
 * Reference bean in parent container
 */
@Test
public void test9(){
    //Parent container
    ApplicationContext pFactory=new ClassPathXmlApplicationContext("beans1.xml");
    //Specify pFactory as the parent container of this container
    ApplicationContext factory=new ClassPathXmlApplicationContext(new String[]{"beans2.xml"},pFactory);
    Boss boss=(Boss) factory.getBean("boss");
    System.out.println("Reference the in the parent container bean");
    System.out.println(boss.getCar().toString());
}

Run this code and print out the following information in the console.

Reference bean in parent container brand: red flag CA72/maxSpeed:200/price:200000.0

Added by tjhilder on Thu, 03 Feb 2022 14:14:42 +0200