在Spring Boot中加載XML配置的完整步驟
開篇
在SpringBoot中我們通常都是基于注解來開發(fā)的,實(shí)話說其實(shí)這個(gè)功能比較雞肋,但是,SpringBoot中還是能做到的。所以用不用是一回事,會不會又是另外一回事。
濤鍋鍋在個(gè)人能力能掌握的范圍之內(nèi),一般是會得越多越好,都是細(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è)配置類,通過配置類加載 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.單元測試
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)行測試方法 成功讀取到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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于kafka-consumer-offset位移問題
這篇文章主要介紹了關(guān)于kafka-consumer-offset位移問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
MyBatis-Plus?實(shí)體類注解的實(shí)現(xiàn)示例
MyBatis-Plus作為MyBatis的增強(qiáng)版,提供了一系列實(shí)用的注解,如@TableName、@TableId、@TableField等,旨在簡化數(shù)據(jù)庫和Java實(shí)體類之間的映射及CRUD操作,通過這些注解,開發(fā)者可以輕松實(shí)現(xiàn)表映射、字段映射、邏輯刪除、自動填充和樂觀鎖等功能2024-09-09
在webservice里調(diào)用耗時(shí)方法出錯的解決方案
這篇文章主要介紹了在webservice里調(diào)用耗時(shí)方法出錯的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
springboot prototype設(shè)置多例不起作用的解決操作
這篇文章主要介紹了springboot prototype設(shè)置多例不起作用的解決操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09

