服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 在Spring Boot中加载XML配置的完整步骤

在Spring Boot中加载XML配置的完整步骤

2020-09-03 00:10涛GuoGuo的跟屁虫丶博Ke Java教程

这篇文章主要给大家介绍了关于在Spring Boot中加载XML配置的完整步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

开篇

在SpringBoot中我们通常都是基于注解来开发的,实话说其实这个功能比较鸡肋,但是,SpringBoot中还是能做到的。所以用不用是一回事,会不会又是另外一回事。

涛锅锅在个人能力能掌握的范围之内,一般是会得越多越好,都是细小的积累,发生质的改变,所以今天和小伙伴们一起分享一下。

实践

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

在Spring Boot中加载XML配置的完整步骤

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

在Spring Boot中加载XML配置的完整步骤

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"
    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 配置文件

?
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

在Spring Boot中加载XML配置的完整步骤

解读

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

在Spring Boot中加载XML配置的完整步骤

另外@ImportResource 这个注解实质上是在包spring-context中的,所以即使项目不是SpringBoot也能使用,当我们使用Java纯配置SSM时,同理可用

总结

到此这篇关于在Spring Boot中加载XML配置的文章就介绍到这了,更多相关Spring Boot加载XML配置内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/doondo/p/13601271.html

延伸 · 阅读

精彩推荐