欢迎来到代码驿站!

当前位置:首页 >

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

时间:2020-09-02 17:00:23|栏目:|点击:

开篇

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

总结

上一篇:vue或react项目生产环境去掉console.log的操作

栏    目:

下一篇:R语言ggplot2边框背景去除的实现

本文标题:在Spring Boot中加载XML配置的完整步骤

本文地址:http://www.codeinn.net/misctech/4442.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有