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
相关推荐
命中的缘分2 分钟前
SpringCloud原理和机制
后端·spring·spring cloud
ErizJ2 分钟前
Golang|分布式索引架构
开发语言·分布式·后端·架构·golang
.生产的驴3 分钟前
SpringBoot 接口国际化i18n 多语言返回 中英文切换 全球化 语言切换
java·开发语言·spring boot·后端·前端框架
Howard_Stark7 分钟前
Spring的BeanFactory和FactoryBean的区别
java·后端·spring
饮长安千年月8 分钟前
学生管理系统审计
java·网络安全·代码审计
-曾牛16 分钟前
Spring Boot中@RequestParam、@RequestBody、@PathVariable的区别与使用
java·spring boot·后端·intellij-idea·注解·spring boot 注解·混淆用法
软件20520 分钟前
【UserDetailsService】
spring boot
新时代苦力工28 分钟前
处理对象集合,输出Map<String, Map<String, List<MyObject>>>格式数据,无序组合键处理方法
java·数据结构·list
极客智谷30 分钟前
Spring AI应用系列——基于Alibaba DashScope的聊天记忆功能实现
人工智能·后端
极客智谷31 分钟前
Spring AI应用系列——基于Alibaba DashScope实现功能调用的聊天应用
人工智能·后端