例自動組立:コンストラクタ

/**
 * 
 * 通过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 + "]";
    }
}

構成メタデータ:

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

出力:System.out.printlnは(context.getBean( "依存"));

分析

実際には、コンストラクタとbyType基本的に同じ。byTypeの場合は、セッター注入により、豆の属性タイプと一致するものを見つけることです。次にコンストラクタを通して注入マッチングコンストラクタによってコンストラクタパラメータタイプ。

上記の書き込みの例が、変更の一例は、前に書き込まbyType場合したがって、モードは自動的に組み立てコンストラクタに変更され、その後、クラスコンストラクタ依存性である追加します。

注:byTypeと同様に、コンストラクタ注入は、非収集および注射のセットに分割され、非コレクションのため、それは豆の同じ種類の2つ以上を持つことができない、あいまいなまたは競合が発生しました。

公開された213元の記事 ウォンの賞賛116 ・は 80000 +を見て

おすすめ

転載: blog.csdn.net/qq2071114140/article/details/104248106