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
相关推荐
customer0814 分钟前
【开源免费】基于SpringBoot+Vue.JS医疗报销系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源
B站计算机毕业设计超人17 分钟前
计算机毕业设计SpringBoot+Vue.jst房屋租赁系统(源码+LW文档+PPT+讲解)
vue.js·spring boot·后端·eclipse·intellij-idea·mybatis·课程设计
barcke23 分钟前
【深度解析】Java接入DeepSeek大模型:从零实现流式对话+多轮会话管理(完整项目实战) —— SpringBoot整合、API安全封装、性能优化全攻略
java·spring boot
zl97989935 分钟前
MybatisPlus-注解
java·spring·maven
杰九1 小时前
【环境配置】maven,mysql,node.js,vue的快速配置与上手
java·vue.js·spring boot·mysql·node.js·maven
wapicn991 小时前
‌挖数据平台对接DeepSeek推出一键云端部署功能:API接口驱动金融、汽车等行业智能化升级
java·人工智能·python·金融·汽车·php
逸狼1 小时前
【JavaEE进阶】Spring DI
java·开发语言
m0_748248651 小时前
SpringBoot整合easy-es
spring boot·后端·elasticsearch
yonuyeung2 小时前
代码随想录算法【Day54】
java·数据结构·算法
敲上瘾2 小时前
基础dp——动态规划
java·数据结构·c++·python·算法·线性回归·动态规划