Spring Boot 中用 XML 定义 Bean
最后更新:2020 年 8 月 3 日
1. 简介
在 Spring 3.0 之前,XML 是定义和配置 bean 的唯一方法。Spring 3.0 引入了 JavaConfig,允许我们使用 Java 类来配置 bean。然而,XML 配置文件至今仍在被使用。
在本教程中,我们将讨论 如何将 XML 配置集成到 Spring Boot 中。
2. @ImportResource 注解
@ImportResource 注解允许我们导入一个或多个包含 bean 定义的资源。
假设我们有一个名为 beans.xml 的文件,其中包含一个 bean 的定义
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean class="com.baeldung.springbootxml.Pojo">
<property name="field" value="sample-value"></property>
</bean>
</beans>
要在 Spring Boot 应用程序中使用它,我们可以 使用 @ImportResource 注解,告诉它在哪里可以找到配置文件
@Configuration
@ImportResource("classpath:beans.xml")
public class SpringBootXmlApplication implements CommandLineRunner {
@Autowired
private Pojo pojo;
public static void main(String[] args) {
SpringApplication.run(SpringBootXmlApplication.class, args);
}
}
在这种情况下,Pojo 实例将被注入在 beans.xml 中定义的 bean。
3. 在 XML 配置中访问属性
如何在 XML 配置文件中使用属性? 假设我们想在 application.properties 文件中声明一个属性
sample=string loaded from properties!
让我们更新 beans.xml 中的 Pojo 定义,以包含 sample 属性
<bean class="com.baeldung.springbootxml.Pojo">
<property name="field" value="${sample}"></property>
</bean>
接下来,让我们验证属性是否正确包含
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootXmlApplication.class)
public class SpringBootXmlApplicationIntegrationTest {
@Autowired
private Pojo pojo;
@Value("${sample}")
private String sample;
@Test
public void whenCallingGetter_thenPrintingProperty() {
assertThat(pojo.getField())
.isNotBlank()
.isEqualTo(sample);
}
}
不幸的是,这个测试会失败,因为 默认情况下,XML 配置文件无法解析占位符。 但是,我们可以通过包含 @EnableAutoConfiguration 注解来解决这个问题
@Configuration
@EnableAutoConfiguration
@ImportResource("classpath:beans.xml")
public class SpringBootXmlApplication implements CommandLineRunner {
// ...
}
此注解启用自动配置并尝试配置 bean。
4. 推荐方法
我们可以继续使用 XML 配置文件。 但我们也可以考虑将所有配置移动到 JavaConfig,原因如下。 首先,在 Java 中配置 bean 是类型安全的,因此我们可以在编译时捕获类型错误。 此外,XML 配置可能会变得非常大,使其难以维护。
5. 结论
在本文中,我们了解了如何使用 XML 配置文件在 Spring Boot 应用程序中定义 bean。
支持本文的代码可在 GitHub 上获取。 一旦你以 Baeldung Pro 会员 身份登录,就开始学习并在项目上进行编码。















