Spring Boot 中加载XML配置

开篇

在SpringBoot中我们通常都是基于注解来开发的,实话说其实这个功能比较鸡肋,但是,SpringBoot中还是能做到的。所以用不用是一回事,会不会又是另外一回事。
涛锅锅在个人能力能掌握的范围之内,一般是会得越多越好,都是细小的积累,发生质的改变,所以今天和小伙伴们一起分享一下。

实践

1.首先我们新建一个SpringBoot Project ,工程名为 xml

2.添加web依赖,点击Finish完成构建

3.我们新建一个类 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.然后在项目的resources目录下,新建一个bean.xml,配置 Say Hello 的实体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.在工程中创建WebMvcConfig,并声明为一个配置类,通过配置类加载 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());
    }

}

运行测试方法 成功读取到xml中的配置Bean

解读

当我们实践完以后我们看一下 ImportResource 这个注解,实质上里面是一个BeanDefinitionReader的接口,而在Spring中这个接口的作用就是读取xml

总结

另外@ImportResource 这个注解实质上是在包spring-context中的,所以即使项目不是SpringBoot也能使用,当我们使用Java纯配置SSM时,同理可用
好了,今天的分享就到这,喜欢的朋友给个支持点个赞,也可通过关注或留言联系涛锅锅,原创不易,谢谢大家!

原文地址:https://www.cnblogs.com/doondo/p/13601271.html