文章目录
一、开篇二、实践1.首先我们新建一个SpringBoot Project ,工程名为 xml2.添加web依赖,点击Finish完成构建3.我们新建一个类 SayHello 不做任何配置4.然后在项目的resources目录下,新建一个bean.xml,配置 Say Hello 的实体Bean5.在工程中创建WebMvcConfig,并声明为一个配置类,通过配置类加载 xml 配置文件6.单元测试
三、解读四、总结
一、开篇
在SpringBoot中我们通常都是基于注解来开发的,实话说其实这个功能比较鸡肋,但是,SpringBoot中还是能做到的。所以用不用是一回事,会不会又是另外一回事。 涛锅锅在个人能力能掌握的范围之内,一般是会得越多越好,都是细小的积累,发生质的改变,所以今天和小伙伴们一起分享一下。
二、实践
1.首先我们新建一个SpringBoot Project ,工程名为 xml
2.添加web依赖,点击Finish完成构建
3.我们新建一个类 SayHello 不做任何配置
package org
.taoguoguo
;
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
;
@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时,同理可用。