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
相关推荐
没有bug.的程序员10 分钟前
分布式架构未来趋势:从云原生到智能边缘的演进之路
java·分布式·微服务·云原生·架构·分布式系统
毕业设计制作和分享2 小时前
springboot150基于springboot的贸易行业crm系统
java·vue.js·spring boot·后端·毕业设计·mybatis
编啊编程啊程4 小时前
【011】宠物共享平台
spring boot·log4j·maven·dubbo·宠物
你的人类朋友7 小时前
【Node】认识multer库
前端·javascript·后端
小梁努力敲代码7 小时前
java数据结构--List的介绍
java·开发语言·数据结构
摸鱼的老谭8 小时前
构建Agent该选Python还是Java ?
java·python·agent
lang201509288 小时前
Spring Boot 官方文档精解:构建与依赖管理
java·spring boot·后端
夫唯不争,故无尤也8 小时前
Tomcat 启动后只显示 index.jsp,没有进入你的 Servlet 逻辑
java·servlet·tomcat
zz-zjx8 小时前
Tomcat核心组件全解析
java·tomcat
Deschen8 小时前
设计模式-外观模式
java·设计模式·外观模式