タイプ別の春のオートワイヤリング

タイプ別のスプリング自動配線

Springでは、「Autowiring by Type」は、Beanのデータ型が他のBeanプロパティのデータ型と互換性がある場合、それを自動配線することを意味します。

たとえば、「person」Beanは「ability」クラスのデータ型のプロパティを公開し、Springは「ability」クラスの同じデータ型のBeanを見つけて自動的に配線します。 一致するものが見つからない場合は、何もしません。

この機能は、以下のようにautowire="byType"を介して有効にできます。

    
    

    
        
    

タイプごとのSpring自動配線の完全な例を参照してください。

1. 豆

2つの豆、人と能力。

package com.example.common;

public class Person
{
    private Ability ability;
    //...
}
package com.example.common;

public class Ability
{
    private String skill;
    //...
}

2. 春の配線

通常、Beanは明示的に配線します。

    
        
    

    
        
    

出力

Person [ability=Ability [skill=Invisible]]

autowire by type enabledを使用すると、能力プロパティを未設定のままにすることができます。 Springは同じデータ型を見つけて、自動的に配線します。

    

    
        
    

出力

Person [ability=Ability [skill=Invisible]]

クラスの「能力」と同じデータ型の2つのBeanがある場合はどうでしょうか。

    

    
        
    

    
        
    

出力

Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException:
...
No unique bean of type [com.example.common.Ability] is defined:
expected single matching bean but found 2: [steal, invisible]; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [com.example.common.Ability] is defined:
expected single matching bean but found 2: [steal, invisible]

この場合、UnsatisfiedDependencyExceptionエラーメッセージが表示されます。

Note
タイプモードによる自動配線では、Beanの一意のデータ型が1つだけ宣言されていることを確認する必要があります。

ソースコードをダウンロード

ダウンロード–Spring-AutoWiring-by-Type-Example.zip(6 KB)