0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

@Autowiredアノテーションについて自分用メモ

Posted at

はじめに

SpringBootの学習を進めていて頻繁に出てくる@Autowiredアノテーションについて、毎回「これなんだっけ?」となっているため、@Autowiredの使い方について自分用メモとしてまとめておき、見返せるようにしておきます。

@Autowiredとは

@Autowiredは依存性注入(DI)を自動的に行ってくれるアノテーションです。

今回依存性注入についての説明は省きます。

@Autowiredアノテーションの使い方

サービス(Service)クラスにリポジトリ(Repository)クラスを依存性注入する例で使い方を見ていきましょう。(import文は省略)

  • SampleRepositoryクラス
@Repository
public class SampleRepository {
    public String getOneName() {
        return "OneUser";
    }
}

※実際にはデータベースからデータを取得するような処理を記述しますが、今回は単純化させるためにただOneUserを返すだけの処理にしている

  • SampleServiceクラス
@Service
public class SampleService {
    @Autowired // ここでインスタンス注入
    private SampleRepository sampleRepository;

    public String passOneName() {
        return sampleRepository.getOneName();
    }
}

このような形で、依存性注入したい箇所に@Autowiredをつけることで、自分でnewすることなく、Springが自動でインスタンスをいれてくれます。


@Autowiredをつけない場合は、下記のようになります。

  • SampleServiceクラス(@Autowiredなし)
@Service
public class SampleService {
    private final SampleRepository sampleRepository;

    // コンストラクタでインスタンス化
    public SampleService(SampleRepository sampleRepository) {
        this.sampleRepository = sampleRepository;
    }

    public String passOneName() {
        return sampleRepository.getOneName();
    }
}

このようにコンストラクタでインジェクションを受け取ります。

@Autowiredを使うために必要なこと

@Autowiredを使うためには

  • DIされる側(例ではリポジトリクラス)とDIする側(例ではサービスクラス)がどちらもDIコンテナに登録されていること
  • DIする側(例ではサービスクラス)のクラス内のフィールドに@Autowiredが使われていること

上記2点が必要となります。
例では@Serviceおよび@Repositoryを使ってDIコンテナに登録されており、サービスクラス内のフィールドに@Autowiredが使われているため、上記2点を満たしますね。

@Atuowiredによるインジェクションの種類

インジェクションの種類が3つあるそうです。

  • フィールドインジェクション
  • セッターインジェクション
  • コンストラクタインジェクション

上記3つについて、現時点では記事を読んでも自分の言葉で書けないため、今後理解を進めてから記事を更新していきたいと思います。

おわりに

今回は@Autowiredアノテーションについて、使い方のメモとしての記事を書きました。
とりあえずフィールドにアノテーションをつけて、自分でnewしなくともDIが行われるという認識をしましたが、まだ使いこなすのは難しそうです。
さらなる理解を深めて、今後記事を更新していきたいと思います。

参考文献

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?