LoginSignup
30
32

More than 5 years have passed since last update.

【Spring】複数のBeanをAutowiredする。(おまけ付き)

Last updated at Posted at 2018-09-24

こんなときに使える

コンテナに登録した複数(0~n個)のBeanを@Autowiredして使いたいとき。

前提

MyServiceインターフェース(doSomethingが定義されている)を実装したクラスが2つ定義されコンテナに登録されてます。


@Component("myServiceImpl1")
public class MyServiceImpl1 implements MyService {

    @Override
    public void doSomething() {
        System.out.println("myServiceImpl1!!")
    }

}

@Component("myServiceImpl2")
public class MyServiceImpl2 implements MyService {

    @Override
    public void doSomething() {
        System.out.println("myServiceImpl2!!")
    }

}

使う側は、この2つを両方@Autowiredして使いたい。しかし、普通に@AutowiredすればBeanの重複エラーで怒られてしまいますし、@Qualifierを付けてこれらを一つずつ@Autowiredするのはナンセンス(用件による)ですね。

ナンセンスなインジェクション例

@Qualifier("myServiceImpl1")
@Autowired
private MyService service1;

@Qualifier("myServiceImpl2")
@Autowired
private MyService service2;

やり方

複数のBeanを@Autowiredするには、@Autowiredする側でListクラスを使います。

MyServiceExecuter.java

@Autowired
private List<MyService> services;

public void execServices(){
    services.forEach(s -> s.doSomething());
}

出力
myServiceImpl1!!
myServiceImpl2!!

おまけ:List以外にも・・・

こうして見てみると、List以外にもジェネリクス使って色々できるクラスはありそうですね。

Mapクラス

Mapクラスに@AutowiredするとKeyがBean名ValueがBeanのMapが取得出来ます。

@Autowired
private Map<String,MyService> services;

public void printServices(){
    services.get("myServiceImpl1").doSomething();
    services.get("myServiceImpl2").doSomething();
}
出力
myServiceImpl1!!
myServiceImpl2!!

Optionalクラス

コンテナに対象Beanが登録されているか分からない。登録されるならそのBeanを使いたいし、無いならインジェクトしなくていいよ。という場合に

@Autowired(required=false)
private MyService service;

required=falseと書くことで、NoSuchBeanDefinitionExceptionが発生するのを回避できるのはご存知の方も多いと思います。が、null安全なコードを書きたいのなら、Optionalを使えばいいじゃない。

@Autowired
private Optional<MyService> service;

こう書けば@Autowiredrequired=falseが要りませんし、何よりnull安全です。

まとめ

Spring DIは奥が深いですね。

サラッと検索した感じ情報載ってなかったのでまとめてみました。

環境↓

springBootVersion = '2.0.5.RELEASE'

【追記】
表現を変更しました。2018.09.24

30
32
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
32