Enterprise 中級

Spring XML Bean設定とアノテーション駆動の比較

冗長なSpring XMLビーン定義をSpring Bootの簡潔なアノテーション駆動設定に置き換える。

✕ Spring (XML)
<!-- applicationContext.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="userRepository"
          class="com.example.UserRepository">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="userService"
          class="com.example.UserService">
        <property name="repository" ref="userRepository"/>
    </bean>

</beans>
✓ Spring Boot 3+
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@Repository
public class UserRepository {
    private final JdbcTemplate jdbc;

    public UserRepository(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }
}

@Service
public class UserService {
    private final UserRepository repository;

    public UserService(UserRepository repository) {
        this.repository = repository;
    }
}
このコードに問題がありますか? お知らせください。
🚫

XMLなし

@SpringBootApplicationがコンポーネントスキャンと自動設定を起動し、すべてのXML配線ファイルを排除します。

💉

コンストラクターインジェクション

Springが自動的にコンストラクターで依存関係を注入するため、ビーンのテストと理解が容易になります。

自動設定

Spring BootがクラスパスからDataSource・JPA・その他のインフラをゼロボイラープレートで設定します。

旧来のアプローチ
XML Beanの定義
モダンなアプローチ
アノテーション駆動Bean
JDKバージョン
17
難易度
中級
Spring XML Bean設定とアノテーション駆動の比較
利用可能

Spring Boot 1.0(2014年4月)以降、広く利用可能。Spring Boot 3はJava 17以上が必要

従来のSpringアプリケーションはXML設定ファイルでビーンを配線し、各クラスと依存関係を冗長な<bean>要素で宣言していました。Spring Boot登場後、自動設定が主流になりました。Spring Bootは@Component・@Service・@Repository・@Controllerアノテーションのビーンをクラスパススキャンで検出し、コンストラクターインジェクションで依存関係を自動解決し、クラスパスからDataSourceなどのインフラを設定します。XMLの配線ファイルはすべて不要になります。

共有 𝕏 🦋 in