Spring Boot学习笔记(八):@ImportResource 注解的使用

        @ImportResource注解:用于导入 Spring 的 xml 配置文件,让该配置文件中定义的 bean 对象加载到Spring容器中。

        比如说:现在有一个 bean.xml 的配置文件,需要将该 beans.xml 中定义的 bean对象 都导入到 Spring Boot 环境的容器中,该如何操作呢?

1.Spring 方式的配置文件 bean.xml 此处随便举个示例,比如说 xml 中配置了一个 helloService,如下所示
<?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">

    <!--将 HelloService 以xml的方式,注入到容器中-->
    <bean id="helloService" class="com.demo.springboot.service.HelloService"></bean>
</beans>
2.使用@ImportResource注解,引入 xml 配置
/**
 * Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别;
 * 如果想让Spring的配置文件生效,加载到Spring 容器中来;
 * 使用@ImportResource注解,将其标注在一个配置类上(此处配置在启动类)
 */
@SpringBootApplication
@ImportResource(locations = {"classpath:beans.xml"})
public class BootApplication {

    public static void main(String[] args) {
        // Spring应用启动起来         
        SpringApplication.run(BootApplication.class,args);

    }
}
3.测试结果

      完成以上两步操作,便已经将 xml 中的 bean对象加载到了 Spring IOC 容器中。
在这里插入图片描述


@ImportResource 注解的使用,介绍到此为止

如果本文对你有所帮助,那就给我点个赞呗

End

发布了301 篇原创文章 · 获赞 66 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/lzb348110175/article/details/105148214