Spring Framework 4.3以降では、単一コンストラクタの場合に限り@Autowiredアノテーションを省略することができます。これは、Springが自動的にそのコンストラクタを使用して依存関係を注入するためです。
唯一のコンストラクタにもかかわらず、@Autowiredアノテーションを使用していると、IDEや静的解析ツールは、このような「冗長な使用」を指摘し、コードのクリーンさを保つためにそれを削除することを推奨します。
以下のように書くことで警告を取り除くことができます:
@RestController
@RequestMapping("/api/sample")
public class SampleController {
private final SampleService sampleService;
// Since there's only one constructor, @Autowired annotation can be omitted.
public SampleController(SampleService sampleService) {
this.sampleService = sampleService;
}
@GetMapping("/data")
public ResponseEntity getSampleData() {
String data = sampleService.getSampleData();
return ResponseEntity.ok(data);
}
}
上記のように@Autowiredが無くても、Springはコンストラクタを通じて適切に依存関係を注入します。
ただし、複数のコンストラクタが存在する場合や、明示的に示す必要がある特定の状況では、@Autowiredを残す必要があります。また、チーム内でのコーディング規約やプロジェクトの慣習に従って、@Autowiredを付けるかどうかを決めることも重要です。