0

私は2つのオブジェクトインジェクションを受け入れるクラスを持っています。そのうちの 1 つは他の Bean ref を介して注入され、もう 1 つは Bean 呼び出しに基づいて注入されます。スプリングを使用してオブジェクトをインスタンス化したい。これどうやってするの ?

私はこれをやってみました:

MyBean クラス:

class MyBean{
    Injection1 ijn1;
    MyBean(Injection1 ijn1,Injection2 ijn2){
      this.ijn1=ijn1;
      this.ijn2=ijn2;
    }
}

Beans.xml

<bean name="myBean" class="MyBean" scope="prototype">
    <constructor-arg>
        <null />
    </constructor-arg>
    <constructor-arg>
        <ref bean="injection2" />
    </constructor-arg>
</bean>


<bean name="injection2" class="Injection2">
</bean>

アプリケーション コード:

MyBean getMyBean(Injection ijn1) {
    return (MyBean)context.getBean("myBean", new Object[] { ijn1 })
}

しかし、これは機能しません。

任意のヒント ?

4

1 に答える 1

1

スプリングは;MyBeanのようなコンストラクターを探すため、コードは機能しません。MyBean(Injection1 ijn1)このように通過する必要がありますinjection2

MyBean getMyBean(Injection ijn1) {
    return (MyBean)context.getBean("myBean", new Object[] { ijn1, context.getBean("injection2") })
}

コードを別の方法で使用したい場合は、次のように部分的に挿入することです。

class MyBean{
    Injection1 ijn1;
    Injection2 ijn2;
    MyBean(Injection1 ijn1){
      this.ijn1=ijn1;
    }

    public void setIjn2(Injection2 ijn2I ) {
      this.ijn2 = ijn2;
    }
}

そしてxmlで

<bean name="myBean" class="MyBean" scope="prototype">
  <property name="inj2" ref="injection2" />
</bean>


<bean name="injection2" class="Injection2">
</bean>
于 2013-08-28T17:53:12.843 に答える