@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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

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);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

3.测试结果

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


博主写作不易,来个关注呗

求关注、求点赞,加个关注不迷路 ヾ(◍°∇°◍)ノ゙



原文链接:https://blog.csdn.net/lzb348110175/article/details/105148214

posted @ 2022-08-21 12:04  独苏  阅读(151)  评论(0编辑  收藏  举报