美文网首页
yaml配置文件

yaml配置文件

作者: ChadJ | 来源:发表于2019-09-27 14:21 被阅读0次

位置

  1. 项目根目录下的config目录中
  2. 项目根目录
  3. classpath下的config目录中
  4. classspath目录
    优先级按照列出的顺序依次降低,如果四个文件都出现,则以优先级高的为准。

2-文件名

默认加载application的配置文件,如果需要自定义文件名,可通过--spring.config.name=[文件名]进行配置。
Idea内可以配置,启动命令末尾添加即可。
java -jar spring-boot.jar --spring.config.name=app

数组注入

yaml支持数组注入,例如

my:
  servers:
    - dev.example.com
    - another.example.com

这段数据可以绑定到一个带Bean的数组中

@ConfigurationProperties(prefix="my")
@Component
public class Config {

    private List<String> servers = new ArrayList<String>();

    public List<String> getServers() {
        return this.servers;
    }
}

对象注入

再集合中存储对象,例如

redis:
  redisConfigs:
    - host: 192.168.66.128
      port: 6379
    - host: 192.168.66.129
      port: 6380

可以注入到类中

@Component
@ConfigurationProperties(prefix = "redis")
public class RedisCluster {
    private List<SingleRedisConfig> redisConfigs;
    //省略getter/setter
}

优缺点

properties文件是无序的,yaml配置是有序的,这一点在有些配置中是非常有用的,例如在Spring Cloud Zuul的配置中,配置代理规则时,顺序就显得尤为重要了。
当然yaml配置也不是万能的,例如,yaml配置目前不支持@PropertySource注解。

相关文章

网友评论

      本文标题:yaml配置文件

      本文链接:https://www.haomeiwen.com/subject/orxauctx.html