SpringBoot引入其他配置文件


  1. @PropertySource
    • 属性

1.value为要加载的文件,可以是多个,当以classpath开头时,程序会自动到classpath中读取,当以file开头时,会加载外部的文件
2.name是表示要加载文件的名称,这里要加载的配置文件必须是 唯一的不能是多个
3.encoding,设置编码,我们一般用utf-8
4.ignoreResourceNotFound,这个属性的意思是当加载的配置文件不存在时,是否报错默认false,当为true时表示文件不存在不报错,为false时表示文件不存在报错

    • 获取单个参数

      使用@Value()注解获取:@Value("${参数名}“”)

    • 批量获取参数 (@ConfigurationProperties)

语法:@ConfiggurationProperties(prefix="参数前缀')

  1. @PropertySources
    • 属性

      value:PropertySource[] value(),是一个PropertySource的集合。

      语法:@PropertySources({ @PropertySource("classpath:配置文件名"),@PropertySource("classpath:配置文件名") })

    • 获取单个参数

      使用@Value()注解获取:@Value("${参数名}“”)

    • 批量获取参数(@ConfigurationProperties)

      语法:@ConfiggurationProperties(prefix="参数前缀')

    • 代码示范
@Configuration
@PropertySources({
        @PropertySource("classpath:MongoDB.properties"),
        @PropertySource("classpath:Redis.properties"),
        @PropertySource("classpath:Mysql.properties")
})
@ConfigurationProperties(prefix = "data")
public class DemoConfig {
    @Value("mysql")
    private String mysql;
    @Value("redis")
    private String redis;
    @Value("mongodb")
    private String mongodb;
    @Bean
    public User user(){
        return new User(mysql,mysql,mongodb);
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM