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!讓我們更新<em>Pojo</em>定義,在<em>beans.xml</em>中包含<em>sample</em>屬性:
<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。