LoginSignup
10
13

More than 5 years have passed since last update.

spring boot初心者にありがちなこと(@ComponentScan編)

Last updated at Posted at 2017-08-07

事象

 コントローラクラスの@RequestMappingが利かなくなり、画面が表示されなくなった。
 パッケージ構成のリファクタリング時に発生。

原因

 @SpringBootApplicationで実行される@ComponentScanについてよく分かっていないまま、パッケージ構成を変更してしまった。

解説

@SpringBootApplicationで実行されるアノテーションは以下の通り。
 @Target(ElementType.TYPE)
 @Retention(RetentionPolicy.RUNTIME)
 @Documented
 @Inherited
 @SpringBootConfiguration
 @EnableAutoConfiguration
 @ComponentScan(excludeFilters = {
  @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
  @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })

 上記のうち、@ComponentScan@Componentのアノテーションが付いたクラスを走査し、利用できるようDIする。
 (コントローラに付加する@Controllerは、@Componentを内包している。)
 @ComponentScanは、@ComponentScanが付いたクラスのパッケージと、その配下のパッケージを走査する。
 今回はコントローラ群のリファクタリング時に、@ComponentScanを並列して存在するパッケージに移してしまった。

▼com.example
 ▼application
  ▼Application.java
 ▼controller
  ▼IndexController.java
  ・・・
 ▼entity
 ・・・

対応

 @ComponentScanを持つApplicationクラスが最上位に来るよう、パッケージ構成をリファクタリング。

▼com.example
 ▼Application.java
 ▼component
  ▼controller
   ▼IndexController.java
   ・・・
  ▼entity
  ・・・

10
13
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
10
13