Spring Boot 中加載XML配置
點(diǎn)擊上方藍(lán)色字體,選擇“標(biāo)星公眾號(hào)”
優(yōu)質(zhì)文章,第一時(shí)間送達(dá)
? 作者?|??cainame?
來(lái)源 |? urlify.cn/7Jn6jm
66套java從入門到精通實(shí)戰(zhàn)課程分享?
一、開(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
四、總結(jié)
另外@ImportResource 這個(gè)注解實(shí)質(zhì)上是在包spring-context中的,所以即使項(xiàng)目不是SpringBoot也能使用,當(dāng)我們使用Java純配置SSM時(shí),同理可用
粉絲福利:108本java從入門到大神精選電子書領(lǐng)取
???
?長(zhǎng)按上方鋒哥微信二維碼?2 秒 備注「1234」即可獲取資料以及 可以進(jìn)入java1234官方微信群
感謝點(diǎn)贊支持下哈?
