Springフレームワークでは、自動配線機能を使ってBeanを自動的に配線することができます。これを有効にするには、<bean>に ”
autowire
“属性を定義します。
<bean id="customer" class="com.mkyong.common.Customer" autowire="byName"/>
Springでは、5つの自動配線モードがサポートされています。
他のbeanプロパティの名前として、それを自動配線します。
-
byType – プロパティデータ型による自動配線。 Beanのデータ型が
他のBeanプロパティのデータ型と互換性があり、自動配線します。
-
コンストラクタ – コンストラクタ引数のbyTypeモード。
-
autodetect – デフォルトのコンストラクタが見つかった場合は、 “autowired by
コンストラクタ”;それ以外の場合は、 “autowire by type”を使用してください。
例
自動配線デモンストレーション用のCustomerオブジェクトとPersonオブジェクト。
package com.mkyong.common;
public class Customer
{
private Person person;
public Customer(Person person) {
this.person = person;
}
public void setPerson(Person person) {
this.person = person;
}
//...
}
package com.mkyong.common;
public class Person
{
//...
}
1.オート配線 ‘no’
これはデフォルトモードです。あなたはbeanを ‘ref’属性で配線する必要があります。
<bean id="customer" class="com.mkyong.common.Customer">
<property name="person" ref="person"/>
</bean>
<bean id="person" class="com.mkyong.common.Person"/>
2.自動配線 ‘byName’
Beanをプロパティ名で自動配線します。この場合、 “person” beanの名前は “customer” beanのプロパティ( “person”)の名前と同じであるため、Springはsetterメソッドを使って自動的に接続します – “` setPerson(Person person) `” 。
<bean id="customer" class="com.mkyong.common.Customer" autowire="byName"/>
<bean id="person" class="com.mkyong.common.Person"/>
完全な例 – リンク://spring/spring-autowiring-by-name/[名前によるSpring Autowiring]を参照してください。
3.自動配線 ‘byType’
Beanをプロパティデータ型で自動配線します。この場合、 “person” Beanのデータ型は “customer” Beanのプロパティ(Personオブジェクト)のデータ型と同じであるため、Springはsetterメソッドを介して自動配線します – “` setPerson(Person person) ` ”
<bean id="customer" class="com.mkyong.common.Customer" autowire="byType"/>
<bean id="person" class="com.mkyong.common.Person"/>
完全な例題 –
Type by Spring autowiring
を参照してください。
4.自動配線 ‘コンストラクタ’
コンストラクタ引数のプロパティデータ型でBeanを自動配線します。この場合、 “person” beanのデータ型は “customer” beanのプロパティ(Personオブジェクト)のコンストラクタ引数のデータ型と同じであるため、Springはコンストラクタメソッドを介して自動配線します – “public Customer(Person person) “
<bean id="customer" class="com.mkyong.common.Customer" autowire="constructor"/>
<bean id="person" class="com.mkyong.common.Person"/>
完全な例 – リンク://spring/spring-autowiring-by-constructor/[コンストラクタによるSpring Autowiring]を参照してください。
5.自動配線「自動検出」
デフォルトのコンストラクタが見つかった場合は、 “コンストラクタ”を使用します。それ以外の場合は、 “byType”を使用します。この場合、 “Customer”クラスにデフォルトのコンストラクタがあるので、Springはコンストラクタメソッド “public customer(Person person)` “を介して自動配線します。
<bean id="customer" class="com.mkyong.common.Customer" autowire="autodetect"/>
<bean id="person" class="com.mkyong.common.Person"/>
完全な例 – リンク://spring/spring-autowiring-by-autodetect/[AutoDetectによるSpring自動配線]を参照してください。
-
Note ** + ‘auto-wire’と ‘dependency-check’の両方を組み合わせてプロパティが常に自動ワイヤリングされていることを確認するのは良いことです。
<bean id="customer" class="com.mkyong.common.Customer"
autowire="autodetect" dependency-check="objects/>
<bean id="person" class="com.mkyong.common.Person"/>
結論
私の見解では、Springの自動配線は開発コストを大幅に高め、Bean構成ファイル全体が複雑になり、どのBeanがどのBeanに自動配線されるのかも分かりません。
実際には、私はむしろそれを手動でワイヤリングします。それは常にきれいで、完全に動作します。より柔軟な
@Autowired annotation
推奨されます。