0

私はこのようなクラスを持っているとしましょう:

public class A {

 private B b;

 public A() {

 }

 // Some code calling methods in b.
}

Spring にパラメーター化されたコンストラクターを追加せずに、XML 構成を介して B のインスタンスを A に挿入するにはどうすればよいですか?

パラメータ化されたコンストラクタとセッターの両方を使用できますか?

 public class A {

     private B b;

     public A(B b) {
        this.b = b;
     }

     public void setB(B b) {
         this.b = b;
     }
     // Some code calling methods in b.
    }

編集:すべての回答に感謝します。私の実際の問題は、次のようなクラスがあることです:

公開クラスA {

 private B b;

 public A(B b) {
    this.b = b;
 }
 // Some code calling methods in b.
}

下位互換性の理由から、パラメーター化されたコンストラクターを削除せずに、上記のクラスのデフォルトのコンストラクターが必要です。

そう 、

  1. Bean を追加すると、Bean はデフォルトのコンストラクターに自動的に注入されますか? または、XML ファイルに挿入する追加の構成が必要ですか?
  2. セッターを追加する場合、XML でどのような追加の構成変更を行う必要がありますか?

以下のようなxmlファイルがあるとします:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="name"
          class="A">
        <constructor-arg ref="B" />
    </bean>

</beans>
4

4 に答える 4

0

次のようなタグを介して、Bean クラス B id をクラス A に渡すことができます<constructor-arg>(たとえば、beans.xml)。

<bean id="a" class="ClassA">
    <constructor-arg ref="beanB"/>
</bean>
<bean id="beanB" class="com.tutorialspoint.SpellChecker">
   </bean>

この点に関しては、次の URL が大いに役立ちます

http://www.tutorialspoint.com/spring/constructor_based_dependency_injection.htm [編集]

于 2013-07-03T05:58:14.670 に答える