Spring Boot 内部メカニズムの全体像

Spring Boot は「自動構成」と「スターター依存」の二つの仕組みによって、Spring アプリケーションの構築を劇的に簡略化している。以下では、その内部で何が起きているのかを俯瞰し、Bean の登録方法から自動構成までを段階的に解説する。

設定ファイルの読み込み順序

アプリケーション起動時に読み込まれる設定ファイルは優先順位が決まっている。

  1. application.properties
  2. application.yml
  3. application.yaml

後のファイルほど優先され、同名プロパティは上書きされる。

Bean の取得方法

Spring 起動後にコンテキストから Bean を取り出す代表的な 3 パターンを示す。

@SpringBootTest
class BeanFetchTest {

    @Autowired
    ApplicationContext ctx;

    @Test
    void fetch() {
        // 1. 名前指定(キャストが必要)
        UserService byName = (UserService) ctx.getBean("userService");

        // 2. 型指定(同一型が複数あると例外)
        UserService byType = ctx.getBean(UserService.class);

        // 3. 名前+型指定(最も安全)
        UserService safe = ctx.getBean("userService", UserService.class);
    }
}

Bean のスコープと遅延初期化

スコープ説明
singletonコンテナ内で唯一のインスタンス(デフォルト)
prototype都度新しいインスタンスを生成
requestHTTP リクエストごと
sessionHTTP セッションごと
@Component
@Scope("prototype")
@Lazy
public class HeavyBean { }

サードパーティクラスを Bean として登録

ライブラリに含まれるクラスを Spring の管理下に置くには @Configuration クラス内で @Bean メソッドを定義する。

@Configuration
public class XmlSupportConfig {

    @Bean
    public SAXReader xmlReader() {
        return new SAXReader();
    }
}

使用側は通常の DI で注入できる。

@Autowired SAXReader reader;

自動構成の仕組み

1. スターター依存

spring-boot-starter-* は Maven の依存関係伝播を利用し、必要なライブラリ一式をまとめて提供する。

2. @EnableAutoConfiguration の働き

Spring Boot はクラスパス上の META-INF/spring.factories を読み込み、EnableAutoConfiguration key に記載された設定クラスを条件付きで登録する。

3. 独自スターターを作る

以下の手順でカスタムライブラリを自動構成可能にする。

  1. 設定クラスを作成
  2. spring.factories に追記
# META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.lib.config.HeaderConfig,\
com.example.lib.config.TokenConfig

条件付き Bean 登録

@Conditional 系アノテーションにより、環境に応じて Bean を有効/無効化できる。

クラスパスの存在チェック

@Bean
@ConditionalOnClass(name = "io.jsonwebtoken.Jwts")
public JwtParser jwtParser() {
    return new DefaultJwtParser();
}

Bean の存在チェック

@Bean
@ConditionalOnMissingBean(name = "customRestTemplate")
public RestTemplate restTemplate() {
    return new RestTemplate();
}

プロパティ値チェック

@Bean
@ConditionalOnProperty(name = "feature.x.enabled", havingValue = "true")
public FeatureX featureX() {
    return new FeatureX();
}

起動クラスと @SpringBootApplication

@SpringBootApplication は以下を合成したメタアノテーションである。

  • @SpringBootConfiguration(= @Configuration
  • @EnableAutoConfiguration
  • @ComponentScan

SpringApplication.run(Main.class, args) は内部で Tomcat を起動し、Main クラスに付与されている @SpringBootApplication を起点に構成を開始する。

タグ: Spring Boot Auto-configuration Bean lifecycle ImportSelector spring.factories

6月21日 16:55 投稿