22.

【Spring】@SpringBootApplicationアノテーションとは

編集
この記事の要点
  • @SpringBootApplication は Spring Boot アプリのメインクラスに付ける
  • 内部で @Configuration + @EnableAutoConfiguration + @ComponentScan をまとめて有効化
  • 自動設定(auto-configuration)が starter 依存から判定して Bean を構成
  • scanBasePackages@ComponentScan 範囲を変更可
  • exclude で不要な自動設定を除外可

 

@SpringBootApplication とは

Spring Boot アプリのメインクラスに付ける、3 つの主要アノテーションをまとめたショートカット:

@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

// これは次と同等
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class MyApp { ... }

3 つの内訳

アノテーション役割
@ConfigurationJavaConfig クラス(@Bean メソッドが使える)
@EnableAutoConfigurationクラスパスや既存 Bean から自動的に必要な Bean を構成
@ComponentScanこのクラスのパッケージ以下をスキャンして @Component を自動登録

自動構成の仕組み

Spring Boot は @EnableAutoConfiguration によって、starter 依存と classpath から「あったら欲しい Bean」を自動構成します:

  • spring-boot-starter-web → 内蔵 Tomcat + DispatcherServlet + Jackson
  • spring-boot-starter-data-jpa → DataSource + EntityManager + Repository スキャン
  • spring-boot-starter-security → Spring Security の標準設定
  • クラスパスに H2 → 自動的にインメモリ DB として接続

有効な自動構成を確認

$ java -jar app.jar --debug

# または application.properties
debug=true

# 出力例(一部):
============================
CONDITIONS EVALUATION REPORT
============================
Positive matches:
  AopAutoConfiguration matched
  DispatcherServletAutoConfiguration matched
  ...
Negative matches:
  RabbitAutoConfiguration:
    Did not match: @ConditionalOnClass classes not found:
      org.springframework.amqp.rabbit.core.RabbitTemplate
  ...

主要な属性

scanBasePackages(ComponentScan 範囲)

// デフォルト: メインクラスのパッケージ以下
@SpringBootApplication
public class MyApp { ... }

// 明示
@SpringBootApplication(scanBasePackages = {"com.example", "com.other"})
public class MyApp { ... }

// クラス指定
@SpringBootApplication(scanBasePackageClasses = {UserService.class, OrderService.class})
public class MyApp { ... }

exclude(自動構成の除外)

// 不要な自動構成を除外
@SpringBootApplication(exclude = {
    DataSourceAutoConfiguration.class,
    HibernateJpaAutoConfiguration.class
})
public class MyApp { ... }

// 名前指定でも可
@SpringBootApplication(excludeName = {
    "org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration"
})

// application.properties で除外
spring.autoconfigure.exclude=\
  org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

メインクラスの場所

メインクラスはパッケージのルートに置くのが原則です:

com/example/
├── MyApp.java          ← @SpringBootApplication
├── controller/
│   └── UserController.java
├── service/
│   └── UserService.java
└── repository/
    └── UserRepository.java

// すべて com.example 配下 → @ComponentScan で自動検出される

// ダメな例:
com/example/controller/MyApp.java  ← controller 配下に置いてしまう
// → service / repository が scan 範囲外になりかねない

SpringApplication の使い方

@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        // 標準起動
        SpringApplication.run(MyApp.class, args);

        // または詳細設定
        SpringApplication app = new SpringApplication(MyApp.class);
        app.setBannerMode(Banner.Mode.OFF);  // バナー非表示
        app.setWebApplicationType(WebApplicationType.NONE);  // CLI アプリ
        app.setAdditionalProfiles("prod");
        app.run(args);

        // または Builder スタイル
        new SpringApplicationBuilder(MyApp.class)
            .bannerMode(Banner.Mode.OFF)
            .web(WebApplicationType.SERVLET)
            .profiles("dev")
            .run(args);
    }
}

関連アノテーション

@SpringBootTest

@SpringBootTest
public class MyServiceTest {
    @Autowired
    private MyService myService;

    @Test
    void testSomething() { ... }
}
// 実 Spring コンテキストを起動してテスト

@EnableScheduling / @EnableAsync

@SpringBootApplication
@EnableScheduling   // @Scheduled を有効化
@EnableAsync        // @Async を有効化
public class MyApp { ... }

// 別クラスで
@Service
public class TaskService {
    @Scheduled(cron = "0 0 * * * *")
    public void hourlyTask() { ... }

    @Async
    public CompletableFuture asyncTask() { ... }
}

@EnableJpaRepositories / @EnableJdbcRepositories

// 通常は Spring Boot が自動有効化するが、明示したい場合
@SpringBootApplication
@EnableJpaRepositories(basePackages = "com.example.repository")
public class MyApp { ... }

main メソッドが必須

Spring Boot の jar 実行には public static void main(String[] args) が必要です:

// pom.xml で実行可能 jar を生成

    org.springframework.boot
    spring-boot-maven-plugin
    
        com.example.MyApp
    


// Gradle
plugins {
    id "org.springframework.boot" version "3.1.0"
}

bootJar {
    mainClass = "com.example.MyApp"
}

関連記事

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. @After
  2. @Autowired
  3. @Bean
  4. @Before
  5. @Column
  6. @Component
  7. @Configuration
  8. @Controller
  9. @Data
  10. @Entity
  11. @GeneratedValue
  12. @Id
  13. @Modifying
  14. @PathVariable
  15. @PropertySource
  16. @Repository
  17. @RequestBody
  18. @RequestMapping
  19. @ResponseBody
  20. @RestController
  21. @Service
  22. @SpringBootApplication
  23. @Table
  24. @Transactional
  25. @Value