Enterprise 中级

Spring XML Bean 配置与注解驱动

用简洁的注解驱动配置替代冗长的 Spring XML bean 定义。

✕ 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。

🔍

就近配置

依赖项在类本身上声明,而非在外部 XML 中。

🧩

自动配置

Spring Boot 自动配置基于 classpath 内容连接常用功能。

旧方式
XML Bean 定义
现代方式
注解驱动 Bean
自 JDK
17
难度
中级
Spring XML Bean 配置与注解驱动
可用

自 Spring Boot 1.0 起广泛可用(2014 年 4 月);Spring Boot 3 需要 Java 17+

传统 Spring 应用通过 XML 配置文件连接 bean,需要大量重复的 <bean> 定义。注解驱动配置(@Component、@Service、@Repository)消除了这些 XML。

分享 𝕏 🦋 in