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
相关推荐
拾忆,想起4 分钟前
Redis复制延迟全解析:从毫秒到秒级的优化实战指南
java·开发语言·数据库·redis·后端·缓存·性能优化
我登哥MVP4 分钟前
Java File 类学习笔记
java·笔记·学习
掘根9 分钟前
【CMake】缓存变量
java·后端·spring
前端开发爱好者12 分钟前
下一代全栈框架:Deno + Vite 的结合体!
前端·javascript·后端
西京刀客15 分钟前
macos安装openjdk17
java·macos·java17
知识浅谈37 分钟前
Redis哨兵模式在Spring Boot项目中的使用与实践
spring boot·redis·bootstrap
Java中文社群1 小时前
面试官:如何实现动态线程池的任务编排?
java·后端·面试
脚踏实地的大梦想家1 小时前
【Go】P2 Golang 常量与变量
开发语言·后端·golang
lozhyf1 小时前
能发弹幕的简单视频网站
java·spring boot·后端
SamDeepThinking1 小时前
Cursor集成MCP MySQL服务器完整配置指南
后端·ai编程·cursor