6
5

More than 1 year has passed since last update.

Springの@Autowiredの方式

Posted at

@Autowiredとは

SpringのDIコンテナから、インスタンスを注入するための指定のこと。
まずDIコンテナとSpringフレームワークの仕組みを知る必要がある。

DIコンテナとは

アプリ起動時にSpringフレームワークが特定のオブジェクトをインスタンス化しており、そのインスタンスを保管してある場所。
次のアノテーションを付けたクラスがインスタンス化の対象。

これらのアノテーションがついたクラスはコードのなかでnew()でインスタンス化することはなく、DIの仕組みによって呼び出し元クラスへ注入される。
それが@Autowiredアノテーションを目印にして行われる。

注入する方法

指定の場所により3種類の方法がある。

種類 場所 備考
コンストラクタインジェクション コンストラクタの前で指定 省略可能(後述)
セッターインジェクション セッターメソッドの前で指定
フィールドインジェクション 変数の前で指定 非推奨とされている

コンストラクタインジェクション

public class MemoController {
    //この方法のみ、finalと指定している。
    private final MemoService memoService;

    @Autowired
    public MemoController(MemoService memoService){
        this.memoService = memoService;
    }

}

セッターインジェクション

public class MemoController {
    private MemoService memoService;

    @Autowired
    public setMemoService(MemoService memoService){
        this.memoService = memoService;
    }

}

フィールドインジェクション

public class MemoController {
    @Autowired
    private MemoService memoService;

}

どの方法を使用すべきか?

コンストラクタインジェクションが推奨される。この方法のみ、final指定で変更不可にできる。
フィールドインジェクションの場合、変数の更新が可能なためそれができない。
セッターインジェクションもメソッドのコール自体はできるので、呼び出し元のコンストラクタで1度のみ実行される方式がもっともよい。

省略が可能

Spring Framework 5.0以降は、コンストラクタインジェクションのみ@Autowiredが省略できる。

public class MemoController {
    private final MemoService memoService;

    //コンストラクタインジェクションは、省略が可能。
    //@Autowired
    public MemoController(MemoService memoService){
        this.memoService = memoService;
    }

}
6
5
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
6
5