温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Spring Boot中实现加载XML配置

发布时间:2020-11-05 16:58:30 来源:亿速云 阅读:637 作者:Leah 栏目:开发技术

如何在Spring Boot中实现加载XML配置?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

开篇

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

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

实践

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

如何在Spring Boot中实现加载XML配置

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

如何在Spring Boot中实现加载XML配置

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

<&#63;xml version="1.0" encoding="UTF-8"&#63;>
<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

如何在Spring Boot中实现加载XML配置

解读

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

如何在Spring Boot中实现加载XML配置

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

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI