在Spring Boot中加載XML配置的完整步驟
開(kāi)篇
在SpringBoot中我們通常都是基于注解來(lái)開(kāi)發(fā)的,實(shí)話說(shuō)其實(shí)這個(gè)功能比較雞肋,但是,SpringBoot中還是能做到的。所以用不用是一回事,會(huì)不會(huì)又是另外一回事。
濤鍋鍋在個(gè)人能力能掌握的范圍之內(nèi),一般是會(huì)得越多越好,都是細(xì)小的積累,發(fā)生質(zhì)的改變,所以今天和小伙伴們一起分享一下。
實(shí)踐
1.首先我們新建一個(gè)SpringBoot Project ,工程名為 xml

2.添加web依賴,點(diǎn)擊Finish完成構(gòu)建

3.我們新建一個(gè)類 SayHello 不做任何配置
package org.taoguoguo;
/**
* @author powersi
* @description SayHello
* @website https://www.cnblogs.com/doondo
* @create 2020-09-02 13:23
*/
public class SayHello {
public String sayHello(){
return "hello xml";
}
}
4.然后在項(xiàng)目的resources目錄下,新建一個(gè)bean.xml,配置 Say Hello 的實(shí)體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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="sayHello" class="org.taoguoguo.SayHello" />
</beans>
5.在工程中創(chuàng)建WebMvcConfig,并聲明為一個(gè)配置類,通過(guò)配置類加載 xml 配置文件
package org.taoguoguo;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
/**
* @author powersi
* @description taoguoguo
* @website https://www.cnblogs.com/doondo
* @create 2020-09-02 13:25
*/
@ImportResource(locations = "classpath:bean.xml")
@Configuration
public class WebMvcConfig {
}
6.單元測(cè)試
package org.taoguoguo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class XmlApplicationTests {
@Autowired
SayHello sayHello;
@Test
void contextLoads() {
System.out.println(sayHello.sayHello());
}
}
運(yùn)行測(cè)試方法 成功讀取到xml中的配置Bean

解讀
當(dāng)我們實(shí)踐完以后我們看一下 ImportResource 這個(gè)注解,實(shí)質(zhì)上里面是一個(gè)BeanDefinitionReader的接口,而在Spring中這個(gè)接口的作用就是讀取xml

另外@ImportResource 這個(gè)注解實(shí)質(zhì)上是在包spring-context中的,所以即使項(xiàng)目不是SpringBoot也能使用,當(dāng)我們使用Java純配置SSM時(shí),同理可用
總結(jié)
到此這篇關(guān)于在Spring Boot中加載XML配置的文章就介紹到這了,更多相關(guān)Spring Boot加載XML配置內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringMvc切換Json轉(zhuǎn)換工具的操作代碼
SpringBoot切換使用goolge的Gson作為SpringMvc的Json轉(zhuǎn)換工具,本文給大家講解SpringMvc切換Json轉(zhuǎn)換工具的操作代碼,感興趣的朋友一起看看吧2024-02-02
Java 高并發(fā)二:多線程基礎(chǔ)詳細(xì)介紹
本文主要介紹Java 高并發(fā)多線程的知識(shí),這里整理詳細(xì)的資料來(lái)解釋線程的知識(shí),有需要的學(xué)習(xí)高并發(fā)的朋友可以參考下2016-09-09
Java中while語(yǔ)句的簡(jiǎn)單知識(shí)及應(yīng)用
這篇文章主要給大家介紹了關(guān)于Java中while語(yǔ)句的簡(jiǎn)單知識(shí)及應(yīng)用的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01

