• springboot之@ImportResource:导入Spring配置文件~


    @ImportResource的作用是允许在Spring配置文件中导入其他的配置文件。通过使用@ImportResource注解,可以将其他配置文件中定义的Bean导入到当前的配置文件中,从而实现配置文件的模块化和复用。这样可以方便地将不同的配置文件进行组合,提高配置文件的可读性和管理性。

    举例:

    
    <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 http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
        <bean id="MyUser1" class="com.springboot.User">
            <property name="name" value="张三">property>
            <property name="age" value="18">property>
        bean>
        <bean id="MyPet1" class="com.springboot.Pet">
            <property name="name" value="小猫">property>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    如上所示为我们在之前学习spring时,通过XML文件的方式进行配置bean,那么这种方法配置的bean是无法通过springboot获取到的,测试如下所示:

    package com.springboot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ConfigurableApplicationContext;
    
    @SpringBootApplication
    public class MainApplication {
        public static void main(String[] args) {
          ConfigurableApplicationContext run= SpringApplication.run(MainApplication.class,args);
          Boolean user1= (Boolean) run.containsBean("MyUser1");
          System.out.println(user1);//输出false
          Boolean pet1= (Boolean) run.containsBean("MyPet1");
          System.out.println(pet1);//输出false
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    为了能够通过springboot获取到该bean,我们可通过下述方法:

    任意的一个自定义的配置类上加上@ImportResource注解,注解中标明XML文件的名称即可!

    @ImportResource("classpath:beans.xml")
    
    • 1

    重新测试后输出均为true

  • 相关阅读:
    【冒泡排序设计】
    PayPal VS Block:开启全球金融科技的新未来
    Vue3——setup 语法检测
    自建网盘平台搭建(源码+教程)
    97. 交错字符串 java解决
    App Store审核被拒的原因和解决方案
    java线程池实战
    设计模式---责任链模式
    go gin ShouldBind 绑定参数到结构体struct 数据校验
    智能IC卡称重系统流程及技术要求
  • 原文地址:https://blog.csdn.net/m0_64365419/article/details/133555566