- XML 配置:Spring 早期和经典的配置方式。
- 注解配置:现代 Spring 开发的主流方式。
- Java 配置(@Configuration):目前官方推荐的、功能最强大的纯 Java 配置方式。
- 自动配置:Spring Boot 的核心特性,简化了配置。
XML 配置
这是 Spring 最原始的配置方式,所有关于 Bean 的定义、依赖关系(注入)、AOP 切面等都写在 XML 文件中。

核心文件
通常命名为 applicationContext.xml 或 spring-config.xml。
主要元素
<beans>: 根元素,是所有 Bean 定义和配置的容器。<bean>: 定义一个 Spring Bean。id: Bean 的唯一标识符。class: Bean 的全限定类名。scope: Bean 的作用域(如singleton,prototype)。
<property>: 用于设置 Bean 的属性,实现依赖注入(Setter 注入)。<constructor-arg>: 用于通过构造函数注入依赖。<import>: 用于导入其他配置文件,实现模块化配置。
示例
假设我们有一个 UserService 和一个 UserRepository。
UserRepository.java
public class UserRepository {
public void save() {
System.out.println("User saved to the database.");
}
}
UserService.java

public class UserService {
private UserRepository userRepository;
// Setter 注入
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
public void addUser() {
userRepository.save();
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!-- 1. 定义 UserRepository Bean -->
<bean id="userRepository" class="com.example.repository.UserRepository"/>
<!-- 2. 定义 UserService Bean,并注入 userRepository -->
<bean id="userService" class="com.example.service.UserService">
<property name="userRepository" ref="userRepository"/>
</bean>
</beans>
测试代码
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
// 加载 Spring 配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 从容器中获取 Bean
UserService userService = context.getBean("userService", UserService.class);
// 调用方法
userService.addUser(); // 输出: User saved to the database.
}
}
优缺点:
- 优点: 配置与代码分离,早期没有 IDE 强力支持时,修改配置无需重新编译代码。
- 缺点: 配置繁琐冗长,文件容易变得巨大且难以维护,可读性差。
注解配置
为了解决 XML 配置的繁琐问题,Spring 2.5 引入了注解,通过在 Java 类或方法上添加注解,Spring 容器可以自动扫描并管理 Bean。

核心注解
@Component: 将一个类标记为 Spring 管理的通用 Bean。@Service: 用于标注服务层组件,是@Component的特例。@Repository: 用于标注数据访问层组件(DAO),是@Component的特例,并提供了异常转换功能。@Controller: 用于标注 MVC 控制器层组件,是@Component的特例。@Autowired: 自动注入,默认按类型(byType)进行注入,如果找到多个相同类型的 Bean,再按名称(byName)匹配。@Value: 用于注入简单值,如配置文件中的属性。@Configuration: 标记一个类作为配置类(见下一节)。@ComponentScan: 在配置类上使用,指定要扫描的包路径,自动注册其中的@Component等注解的 Bean。
示例
基于上面的例子,使用注解改造:
UserRepository.java
import org.springframework.stereotype.Repository;
@Repository // 标记为数据访问层 Bean
public class UserRepository {
public void save() {
System.out.println("User saved to the database.");
}
}
UserService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service // 标记为服务层 Bean
public class UserService {
// 自动注入 UserRepository Bean
@Autowired
private UserRepository userRepository;
public void addUser() {
userRepository.save();
}
}
配置类 AppConfig.java
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration // 标记此类为配置类
@ComponentScan("com.example") // 扫描 com.example 包及其子包下的所有组件
public class AppConfig {
// 这个类现在是空的,Spring 会自动处理 Bean 的创建和注入
}
测试代码
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainApp {
public static void main(String[] args) {
// 加载配置类
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = context.getBean(UserService.class);
userService.addUser(); // 输出: User saved to the database.
}
}
优缺点:
- 优点: 配置简洁,与代码结合更紧密,IDE 支持好,开发效率高。
- 缺点: 配置与代码耦合,对于复杂的第三方库配置,有时不如 XML 灵活。
Java 配置 (@Configuration)
这是目前官方推荐的配置方式,它完全使用 Java 代码来定义配置,而不是 XML 或注解,它结合了 XML 的清晰结构和注解的简洁性。
核心注解
@Configuration: 声明当前类是一个 Spring 配置类,相当于一个 XML 配置文件。@Bean: 在配置类中,标注一个方法,方法的返回值会注册为 Spring 容器中的一个 Bean,默认方法名就是 Bean 的 ID。@Profile: 根据环境(如dev,prod)来定义不同的 Bean。@Import: 导入其他配置类。
示例
我们用 Java 配置来实现同样的功能:
UserRepository.java (和之前一样)
@Repository
public class UserRepository {
public void save() { /* ... */ }
}
UserService.java (和之前一样)
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
// ...
}
配置类 AppConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.example") // 仍然可以使用 @ComponentScan 来扫描组件
public class AppConfig {
// 如果某个类没有 @Component 等注解,或者需要手动创建和配置 Bean,可以使用 @Bean
// 手动配置一个数据源
@Bean
public UserRepository userRepository() {
return new UserRepository();
}
// @Bean 方法可以相互依赖
@Bean
public UserService userService(UserRepository userRepository) {
UserService service = new UserService();
// 这里手动注入,或者让 UserService 的 @Autowired 自动注入
// service.setUserRepository(userRepository);
return service;
}
}
测试代码:与注解配置中的测试代码完全相同。
优缺点:
- 优点: 类型安全,可重构,功能强大(可以编写任何 Java 逻辑来配置 Bean),是 Spring Boot 的基础。
- 缺点: 对于非常简单的项目,可能感觉有些“重”。
自动配置
这是 Spring Boot 的核心特性,旨在彻底简化 Spring 应用的配置,它基于“约定优于配置”的原则。
工作原理
Spring Boot 在启动时会自动扫描 classpath 下的所有 jar 包,并根据你引入的依赖(JAR 包)自动配置相应的 Bean。
- 如果你引入了
spring-boot-starter-web,Spring Boot 会自动配置:DispatcherServletTomcat服务器Jackson(用于 JSON 序列化)MessageSource(用于国际化)- 等等...
- 如果你引入了
spring-boot-starter-data-jpa,它会自动配置:EntityManagerFactoryTransactionManagerJpaRepositories(自动扫描@Repository接口)
如何实现?
自动配置主要由两个注解驱动:
@EnableAutoConfiguration: 在 Spring Boot 的主类(带有@SpringBootApplication的类)上,此注解默认被包含,它负责开启自动配置。@SpringBootApplication: 这是一个复合注解,包含了@EnableAutoConfiguration,@ComponentScan,@Configuration。
如何自定义自动配置?
自动配置不是黑魔法,你可以很轻松地覆盖它:
- 定义自己的 Bean: 你在自己的配置类中定义一个同名的 Bean,Spring Boot 会优先使用你定义的 Bean。
- 使用
@Conditional系列注解: 在自动配置类中,大量使用了@ConditionalOnClass,@ConditionalOnMissingBean等条件注解来控制 Bean 的创建,你可以通过application.properties或application.yml文件来禁用某个特定的自动配置项。
配置文件:application.properties / application.yml
这是 Spring Boot 的核心配置文件,用于覆盖默认的自动配置和定义应用自己的配置。
application.properties 示例
# 服务器端口 server.port=8081 # 数据库配置 spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=password # JPA 配置 spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
application.yml 示例 (YAML 格式,更结构化)
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: password
jpa:
hibernate:
ddl-auto: update
show-sql: true
总结与演进路径
| 配置方式 | 核心技术 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|---|
| XML 配置 | <beans>, <bean>, <property> |
配置与代码解耦,清晰 | 繁琐、冗长、维护困难 | 遗留系统、复杂第三方库集成 |
| 注解配置 | @Component, @Service, @Autowired |
简洁、开发效率高、IDE 支持 | 配置与代码耦合 | Spring Framework 项目(非 Boot)的主流方式 |
| Java 配置 | @Configuration, @Bean |
类型安全、可重构、功能强大 | 对简单项目略显复杂 | Spring Framework 推荐方式,Spring Boot 的基础 |
| 自动配置 | @SpringBootApplication, application.yml |
极致简化、开箱即用 | "魔法"感强,需要理解原理才能定制 | Spring Boot 项目,现代微服务开发的首选 |
演进路径:
XML -> 注解 -> Java 配置 -> 自动配置
对于现代 Spring 开发,特别是使用 Spring Boot 的情况,你几乎不需要编写任何 XML 或 @Bean 定义,你只需要:
- 在主类上添加
@SpringBootApplication。 - 在业务类上添加
@Service,@Repository等注解。 - 在
application.yml或application.properties文件中进行少量必要的配置。
Spring Boot 会帮你处理好剩下的一切。
