4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Spring Boot アノテーション学習用

Last updated at Posted at 2019-06-20

自分の学習用です。

今のプロジェクトでSpring使い始めました。

Java , Springの特徴であるアノテーションをよくわかってない=>
効率的な実装ができない。Springを有効活用できていない。

App.javaにあるやつ
@SpringBootApplication
このアノテーションがついているクラスはSpring Bootのアプリケーションクラスであることを示します。
Springをbootさせるrunメソッドがある。
実行時に様々な設定情報を追加したいときに使う。

@EnableScheduling
スケジュール機能を有効にする。->@Scheduledの使用を許可

@Scheduled
メソッドの実行時間を指定可能。
アノテーションに以下の引数をとることで定期実行ができる。
cronも使える。
詳細⇒https://qiita.com/rubytomato@github/items/4f0c64eb9a24eaceaa6e

Lombok(GetterやSetterを自動的に作ってくれるやつ)関連のアノテーション
3種類あります。
@NoArgsConstructor,@RequiredArgsConstructor, @AllArgsConstructor

これらの3つは、lombokでgetter/setterを作る際のコンストラクタを自動生成してくれるアノテーションです。

@NoArgsConstructor 引数無しのデフォルトコンストラクタを生成。
@RequiredArgsConstructorは、finalがついたフィールドへ値をセットするための引数がついたコンストラクタを生成。
@AllArgsConstructor 全フィールドに対する初期化値を引数にとるコンストラクタを生成

RequiredArgsConstructorの挙動

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class Employee {

    private final int id;

    private String name;
}

生成されるコード

public class Employee {
    private final int id;
    private String name;

    public Employee(final int id) {
        this.id = id;
    }
}
//final修飾子がついていないnameはコンストラクタに含まれていない。

進行中のPJでは
@RequiredArgsConstructor(onConstructor = @__(@Autowired))の形で使われています。

onConstructor = @__(@Autowired))って何だ(?)と思ったので調べてみました。
Lambokの公式のドキュメントによると、生成されたコンストラクタにアノテーションをつけるために置いているらしいです(!?)
https://projectlombok.org/features/constructor
onX -> OnConstructorについては、以下のように書いてありました。
"we heard you like annotations, so we put annotations in your annotations so you can annotate while you're annotating."
"我々はあなたがアノテーションのことが好きだと聞いたので、あなたのアノテーションの中にアノテーションを入れておいた。なので、あなたは、アノテーションしている間もアノテーションできるのだ。"

4
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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?