SpringBoot中@Import和@ImportResource和@PropertySource

1. @Import

@Import注解是引入java类:

  • 导入@Configuration注解的配置类(4.2版本之前只可以导入配置类,4.2版本之后也可以导入普通类)

  • 导入ImportSelector的实现类

  • 导入ImportBeanDefinitionRegistrar的实现类

    @SpringBootApplication
    @Import(MyCustomize.class)
    public class StartBootReadConfig {

    复制代码
      public static void main(String[] args) {
          SpringApplication.run(StartBootReadConfig.class, args);
      }
      
      @Autowired
      MyCustomize myCustomize;
    
      @PostConstruct
      public void init(){
          myCustomize.printf();
      }

    }

2. @ImportResource

@ImportResource是引入spring配置文件.xml,它导入的是使用xml配置文件注入的对象。

新建测试类:

复制代码
public class MyCustomize {

    public void printf(){
        System.out.println("MyCustomize.printf");
    }
}

新建一个bean的配置文件mycustomize.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 id="mycustomize" name="mycustomize" class="com.lx.readconfig.service.MyCustomize">
    </bean>
</beans>

使用ImportResource导入:

复制代码
@SpringBootApplication
@ImportResource("mycustomize.xml")
public class StartBootReadConfig {

    public static void main(String[] args) {
        SpringApplication.run(StartBootReadConfig.class, args);
    }

    @Autowired
    MyCustomize myCustomize;

    @PostConstruct
    public void init(){
        myCustomize.printf();
    }

}

3.@PropertySource

@PropertySource是引入自定义配置文件(yml或properties),用于spring boot 配置文件(yml或properties)与实体属性映射。

复制代码
@Component
//@PropertySource("classpath:myext.properties")
//PropertySource默认不支持yml或者yaml的解析
@PropertySource(value = "classpath:myext.yml", factory = CustomizePropertySourceFactory.class)
@ConfigurationProperties(prefix = "keyfieldpropertiesext")
@Data
相关推荐
陈果然DeepVersion3 分钟前
Java大厂面试真题:从Spring Boot到AI微服务的三轮技术拷问(二)
spring boot·redis·spring cloud·微服务·ai·java面试·rag
moiumxf0278q4 分钟前
C++中智能指针是如何工作的?
java·jvm·c++
尼古拉斯·纯情暖男·天真·阿玮35 分钟前
泛型与数据结构
java·数据结构
用户693717500138444 分钟前
Kotlin 协程基础入门系列:从概念到实战
android·后端·kotlin
Q_Q19632884751 小时前
python+django/flask的医院财务管理系统
spring boot·python·django·flask·node.js
半旧夜夏1 小时前
【Gateway】服务调用和网关配置攻略
java·spring boot·spring cloud·gateway
Moonbit1 小时前
MoonBit Pearls Vol.14:哈希表避坑指南
后端·算法·编程语言
yue0081 小时前
C# 求取整数的阶乘
java·开发语言·c#
Moonbit1 小时前
MoonBit Pearls Vol.13: 使用 MoonBit 开发一个 HTTP 文件服务器
服务器·后端·http