阅读完需:约 1 分钟
本来再springboot里面是不需要xml文件的配置的,可以说是根本不用的,但是有些杠精说一定要用呢?那那那那。。。也可以用哈!
来看一下小例子:
首先要创建一个类SayHello
package cn.xml;
public class SayHello {
public String sayhello(){
return "hello xml";
}
}
下面是创建xml文件
<?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 class="cn.xml.SayHello" id="sayHello"></bean>
</beans>
其实就是spring的xml头文件再加上点东西
下面是创建WebMvcConfig
@Configuration
@ImportResource(locations = "classpath:beans.xml")
public class WebMvcConfig
{
}
这个文件啥也不用写,主要是加上@ImportResource(locations = "classpath:beans.xml")
来启用xml文件
最后是测试了:
@SpringBootTest
class XmlApplicationTests {
@Autowired
SayHello sayHello;
@Test
void contextLoads() {
System.out.println(sayHello.sayhello());
}
}
结果:
其实这个东西不关springboot啥事,从spring开始就有了