Example automatic assembly: constructor

/**
 * 
 * 通过constructor自动装配进行注入
 * 
 * collaboratorBean 单个bean,在配置元数据中不能有多个同类型的bean,否则会出错
 * set 集合,将多个同类性的bean注入这个集合(array)中
 */

public class Dependent {

    private Collaborator collaboratorBean;
    private SetElement[] set ;

    public Dependent(Collaborator collaboratorBean, SetElement[] set) {
        super();
        this.collaboratorBean = collaboratorBean;
        this.set = set;
    }

    @Override
    public String toString() {
        return "Dependent [collaboratorBean=" + collaboratorBean + ",\n\tset=" + Arrays.toString(set) + "\n]";
    }
}

public class Collaborator {
    private String info;

    public void setInfo(String info) {
        this.info = info;
    }

    public String toString() {
        return "Collaborator [info=" + info + "]";
    }
}

public class SetElement {
    private String info;

    public void setInfo(String info) {
        this.info = info;
    }

    public String toString() {
        return "SetElement [info=" + info + "]";
    }
}

Configuration metadata:

<bean id="dependent" class="SpringTest.autoWire.byType.Dependent" autowire="constructor"/>

<!-- 将单个的bean注入 -->
<bean id="one" class="SpringTest.autoWire.byType.Collaborator">
    <property name="info" value="This is collaboratorBean"/>
</bean>


<!-- 下面的3个bean被注入到集合中 -->
<bean id="element1" class="SpringTest.autoWire.byType.SetElement">
    <property name="info" value="element1"/>
</bean>

<bean id="element2" class="SpringTest.autoWire.byType.SetElement">
    <property name="info" value="element2"/>
</bean>

<bean id="element3" class="SpringTest.autoWire.byType.SetElement">
    <property name="info" value="element3"/>
</bean>

Output: System.out.println (context.getBean ( "dependent"));

analysis

In fact, constructor and byType basically the same. For byType, it is to find a match with the attribute type of bean, by setter injection. constructor parameter type by matching constructor then injected through the constructor.

Therefore, when the write example above, but an example of changes byType written before, the mode is automatically changed to the assembly constructor, and then to add the class constructor is Dependent.

Note: As with byType, constructor injection is also divided into a set of non-collection and injection, for non-collection, it can not have two or more of the same kind of bean, ambiguous or conflict occurs.

Published 213 original articles · won praise 116 · views 80000 +

Guess you like

Origin blog.csdn.net/qq2071114140/article/details/104248106