在Spring Boot应用中,虽然官方推荐使用注解和Java Config来完成Bean的定义与依赖注入,但在实际项目中经常会遇到需要兼容旧系统或复用已有XML配置文件的场景。Spring Boot并没有移除对XML配置的支持,而是通过简单的机制让我们继续读取并使用这些配置。

使用@ImportResource引入XML配置
最常见的方式是在主启动类或者某个配置类上添加@ImportResource注解,指定XML文件的位置。这样Spring容器在启动时就会解析该XML并把其中定义的Bean注册到上下文中。
// 主启动类
@SpringBootApplication
@ImportResource(locations = {"classpath:applicationContext.xml"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
对应的XML配置文件示例如下,注意其中的标签需要使用标准Spring beans命名空间:
<?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">
<bean id="userService" class="com.example.demo.UserService">
<property name="message" value="从XML加载的Bean"/>
</bean>
</beans>
在业务代码中获取XML定义的Bean
当XML中的Bean被成功加载后,我们可以像使用普通Spring Bean一样通过@Autowired或者ApplicationContext来获取它。
@Service
public class ClientService {
@Autowired
private UserService userService;
public void print() {
System.out.println(userService.getMessage());
}
}
手动加载XML配置上下文
如果不想使用@ImportResource,也可以在代码中手动创建基于XML的ApplicationContext,适合在工具类或测试场景中使用。
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class XmlLoader {
public static void main(String[] args) {
// 手动加载classpath下的XML配置
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
UserService service = context.getBean(UserService.class);
System.out.println(service.getMessage());
}
}
两种方式的对比
| 方式 | 适用场景 | 集成程度 |
|---|---|---|
| @ImportResource | Spring Boot主应用兼容旧XML | 高,与自动配置融合 |
| ClassPathXmlApplicationContext | 测试、独立工具、局部加载 | 低,独立上下文 |
注意事项
- XML中定义的Bean id不要与Java Config或注解扫描的Bean重复,否则会引发冲突。
- 如果XML里引用了外部属性文件,需要确保
PropertySourcesPlaceholderConfigurer已正确配置。 - 在Spring Boot中混用XML和注解时,建议将XML仅用于遗留模块,新功能尽量采用注解。
Spring Boot对XML的支持是向后兼容的设计,合理使用可以降低迁移成本。
小结
通过@ImportResource注解或手动加载ClassPathXmlApplicationContext,Spring Boot可以轻松读取并使用XML配置文件。开发者无需完全重写旧配置,就能在现代化框架中继续使用原有Bean定义,实现平滑过渡。
Spring_BootXML配置Bean加载修改时间:2026-07-26 13:06:19