開篇
在SpringBoot中我們通常都是基于注解來開發(fā)的,實話說其實這個功能比較雞肋,但是,SpringBoot中還是能做到的。所以用不用是一回事,會不會又是另外一回事。
濤鍋鍋在個人能力能掌握的范圍之內(nèi),一般是會得越多越好,都是細小的積累,發(fā)生質(zhì)的改變,所以今天和小伙伴們一起分享一下。
實踐
1.首先我們新建一個SpringBoot Project ,工程名為 xml
2.添加web依賴,點擊Finish完成構(gòu)建
3.我們新建一個類 SayHello 不做任何配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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.然后在項目的resources目錄下,新建一個bean.xml,配置 Say Hello 的實體Bean
1
2
3
4
5
6
7
8
|
<? xml version = "1.0" encoding = "UTF-8" ?> < beans xmlns = "http://www.springframework.org/schema/beans" 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,并聲明為一個配置類,通過配置類加載 xml 配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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.單元測試
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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()); } } |
運行測試方法 成功讀取到xml中的配置Bean
解讀
當我們實踐完以后我們看一下 ImportResource 這個注解,實質(zhì)上里面是一個BeanDefinitionReader的接口,而在Spring中這個接口的作用就是讀取xml
另外@ImportResource 這個注解實質(zhì)上是在包spring-context中的,所以即使項目不是SpringBoot也能使用,當我們使用Java純配置SSM時,同理可用
總結(jié)
到此這篇關(guān)于在Spring Boot中加載XML配置的文章就介紹到這了,更多相關(guān)Spring Boot加載XML配置內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://www.cnblogs.com/doondo/p/13601271.html