Spring Bootでよく使うアノテーション一覧
@Controller
画面遷移用のコントローラーに付与する
@RestController
Webアプリケーションにおいてリクエストを受け付ける「コントローラークラス」にに付与する
@RequestMapping("パス")
@Controller・@RestControllerを付与したクラスがマッピングするURLの接頭辞を設定
【使用例】
@Controller
@RequestMapping("sample")
public class SampleController {
...
@GetMapping("パス")
HTTPリクエストのGETメソッドを受け付けるためのメソッドに付与
【使用例】
@Controller
public class ExampleController {
@GetMapping("hogehoge")
String index() {
.
.
return "example";
}
}
@PostMapping("パス")
HTTPリクエストのPOSTメソッドを受け付けるためのメソッドに付与
【使用例】
@Controller
public class ExampleController {
@PostMapping("fugafuga")
String index() {
.
.
return "example";
}
}
@Service
サービスクラスに付与
【使用例】
@Service
public class ExampleService {
public List<Customer> getCustomer() {
・
・
return customerList;
}
}
@ComponentScan
そのクラスのパッケージ以下の@Component等、特定のアノテーションが付与されたクラスのBeanをDIコンテナに登録する
【代表的なアノテーション】
- @Component
- @Controller
- @Service
- @Repository
- @Configuration
@Bean
DIコンテナに管理させたい「Bean」を生成するメソッドに付与する
※メソッド名がBean名になる
※singletonとして管理され、DIコンテナに1つのインスタンスのみ生成される
【使用例】
@Bean Animal animal() { return new Animal(); }
@Data
コンパイル時に下記メソッドが生成する
- setter()メソッド
- getter()メソッド
- toString()メソッド
- equals()メソッド
- hashCode()メソッド
※Lombokのインストールが必要
@Autowired
特定のアノテーションを付与したクラスのインスタンスを使用できるようにする
Springの肝となるアノテーションの1つ
詳細はこちら
SpringBoot入門 vol.8:DIを理解しよう
@ModelAttribute
返り値は自動的にModelに追加される
@RequestMappingでマッピングされたメソッドの前に実行される
【使用例】
デフォルトではクラス名の最初の文字を小文字にした属性名がModelに追加される
下記の場合、属性名は「sampleForm」
@ModelAttribute
SampleForm sampleForm() {
return new SampleForm();
}
@ModelAttributeに属性名を付与することも可能
下記の場合、属性名は「anotherForm」
@ModelAttribute("anotherForm")
SampleForm sampleForm() {
return new SampleForm();
}
@Validated
@NotNullや@Size等、「Bean Vvalidation」アノテーションが評価され、結果が「BindingResult」に格納される
【使用例】
String sample(@Validated SampleForm sampleform, BindingReuslt result, Model model) {
<メソッドの内容を記述>
}
@PathVariable
REST形式のパラメーターを受け取る
【使用例】
例)http:hogehoge/get/1
//{id}で動的にパラメーターを取得
@RequestMapping("get/{id}")
public Users findOne(@PathVariable("id") Integer id) {
//idに「1」が設定されている
Users user = usersMapper.selectByPrimaryKey(id);
return user;
}
@RequestParam
リクエストパラメーターを受け取る
【使用例】
例)http:hogehoge/get?id=1
@RequestMapping("get")
public Users findOne(@RequestParam("id") Integer id) {
Users user = usersMapper.selectByPrimaryKey(id);
return user;
}
@Entity
JPAのエンティティであることを示す
※エンティティクラスに指定
【使用例】
「ID」・「NAME」をカラムに持つcustomerテーブルのエンティティクラスの場合
@Entity
public class Customer {
@Id
private Integer id;
private String name;
}
@Table(name = "テーブル名")
エンティティに対応するテーブル名を指定
※クラス名がテーブル名でない時に使用
【使用例】
「ID」・「NAME」をカラムに持つsampleテーブルで、エンティティクラス名が「Customer」の場合
@Entity
@Table(name = "sample")
public class Customer {
@Id
private Integer id;
private String name;
}
@GeneratedValue
オートインクリメント
※注意点
MySQL等でオートインクリメントを設定している場合は下記エラーが出る場合がある
「java.sql.SQLSyntaxErrorException: Table ‘<データベース名>.hibernate_sequence’ doesn’t exist」
※原因
hibernateはデフォルトのhibernate_sequenceテーブルを探す為
※対処法
「strategy = GenerationType.IDENTITY」を追記する
@GeneratedValue(strategy = GenerationType.IDENTITY)
@SequenceGenerator(name = "シーケンス名", allocationSize = 1)
シーケンス設定
※allocationSize:シーケンスオブジェクトの増分間隔と同じ値を指定する
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "シーケンス名")
「SEQ_ID」で自動採番
@Transactional
クラスに付与するとそのクラス内のメソッドが他のクラスから呼ばれた場合にDBトランザクション制御を行う
★実行時例外が発生した場合はロールバックされるが、チェック例外の場合はロールバックされないので注意が必要
チェック例外とは「Runtime Exception」系以外の例外
例)
・NullPointerException、IllegalArgumentException等
・チェック例外
⇒IOException、SQLException等
@AllArgsConstructor
全フィールドを引数に持つコンストラクタを生成する
※Lombokを依存関係に追加する必要あり
@NoArgsConstructor
引数がないコンストラクタを生成する
★JPAの仕様でエンティティクラスには引数のないデフォルトコンストラクタを作成する必要がある
もし無い場合は「No default constructor for entity」エラーとなるので注意
※Lombokを依存関係に追加する必要あり
@Column
DBカラムに名前や制約を設定
【使用例(NOT NULL制約)】
@Column(nullable = false)
@Query("JPQL")
データへのアクセスを自作する際に使用する
前提条件
・JpaRepositoryクラスを継承する
・型は<エンティティ名, Integer>
【使用例】
「Customer」テーブルを「ID」降順でSELECTしたfindAllOrderByIdDesc()メソッドを作成
package com.example.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.example.domain.Customer;
public interface CustomerRepository extends JpaRepository<Customer, Integer> {
//ID降順のselect文 ※ORDER BY句で指定している「id」はプロパティ名の為、小文字になる
@Query("SELECT u FROM Customer u ORDER BY u.id DESC")
List<Customer> findAllOrderByIdDesc();
}
@NotNull
Bean Validationの1つ
Nullチェックのアノテーション
パラメーターが送られてこない場合にエラーにする
@NotEmpty
Null、空文字でないことをチェック
@NotBlank
Null、空文字、半角スペースでないことをチェック
@Size(min = <文字列長>, max = <文字列長>)
Bean Validationの1つ
文字数を制限するアノテーション
※バイト数ではなく文字数である点に注意
【使用例】
1文字以上、20文字以下に制限する場合
@Size(min = 1, max = 20)
private String name;
〇〇@〇〇形式かをチェック
@AssertTrue
Trueかをチェック
@AssertFalse
Falseかをチェック
@Pattern
指定の正規表現に一致するかをチェック
【使用例】
半角英数字のみの場合
@Pattern(regexp = "^[a-zA-Z0-9]+$")
@DateTimeFormat
日付形式をチェック
【使用例】
yyyy/MM/dd形式の場合
@DateTimeFormat(pattern = "yyyy/MM/dd")
24時間表記の「時間:分」の場合
@DateTimeFormat(pattern = "HH:mm")
@SpringBootApplication
Spring Bootの様々な設定を自動的に有効にする
具体的には下記3つのアノテーションの組合せ
- @EnableAutoConfiguration
- @Configuration
- @ComponentScan
@EnableAutoConfiguration
Spring Bootの様々な設定を自動的に有効にする
@Configuration
JavaConfig用のクラスであることを示す
※JavaConfig:Beanを定義するクラス
@Qualifier("Bean名")
同じ型のBeanがDIコンテナに複数登録されている場合に適用するBeanを指定するアノテーション
【使用例】
設定ファイル(AppConfig.java)に複数のBeanがDIされいる場合
@Configuration
@ComponentScan
public class AppConfig {
//同じPasswordEncoder型のBeanをDIコンテナに複数登録
//「bCryptPasswordEncoder」という名前のBeanをDIコンテナに登録
@Bean
PasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
//「pbkdf2PasswordEncoder」という名前のBeanをDIコンテナに登録
@Bean
PasswordEncoder pbkdf2PasswordEncoder() {
return new Pbkdf2PasswordEncoder();
}
}
起点クラス(SampleController.java)の@QualifierでBeanを指定
@RestController
public class SampleController implements UserDetailsService{
@Autowired
//Beanを指定
@Qualifier("bCryptPasswordEncoder")
PasswordEncoder passwordEncoder;
@GetMapping
public String index() {
return "Hello";
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return null;
}
}