Spring Boot (二十三)——加载XML配置

前言

在使用springboot的时候一般是极少需要添加配置文件的(application.properties除外),但是在实际应用中也会存在不得不添加配置文件的情况,例如集成其他框架或者需要配置一些中间件等,在这种情况下,我们就需要引入我们自定义的xml配置文件了。

实现

看一个最简单的例子,不用注解,使用xml的方式给容器中注入一个bean:

首先,准备一个bean,不要注解:

public class Hello {
    public void sayHello(){
        System.out.println("hello macay");
    }
}

在resource目录下创建一个bean.xml:

<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 name="hello" class="com.macay.xml.Hello"></bean>
</beans>

创建一个配置类,使用@ImportResource注解加载一个XML:

@Configuration
@ImportResource(value = "classpath:bean.xml")
public class MvcConfig {

}

测试一下,看Hello对象有没有注入容器中:

@SpringBootTest
class XmlApplicationTests {
    @Autowired
    Hello hello;

    @Test
    void contextLoads() {
        hello.sayHello();
    }
}

测试结果如下:
在这里插入图片描述
说明XML文件已加载,Hello对象一杯注入Spring容器中。

发布了60 篇原创文章 · 获赞 0 · 访问量 578

猜你喜欢

转载自blog.csdn.net/weixin_44075963/article/details/103923680