当前位置: 移动技术网 > IT编程>开发语言>Java > 在Spring Boot中加载XML配置的完整步骤

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

2020年09月03日  | 移动技术网IT编程  | 我要评论
开篇在springboot中我们通常都是基于注解来开发的,实话说其实这个功能比较鸡肋,但是,springboot中还是能做到的。所以用不用是一回事,会不会又是另外一回事。涛锅锅在个人能力能掌握的范围之

开篇

在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时,同理可用

总结

到此这篇关于在spring boot中加载xml配置的文章就介绍到这了,更多相关spring boot加载xml配置内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网