• 使用YAML配置Spring boot的外部属性


    说明:

    YAML是JSON的一个超集,可以非常方便地将外部配置以层次结构形式存储起来。当项目的类路径中有SnakeYAML库(springbootstarter中已经被包含)时,SpringApplication类将自动支持YAML作为properties的替代。

    如果将项目中的application.properties文件修改为YAML文件(尾缀为.yml或yaml)的形式,则其配置信息就如同下面两个文件所示:

    使用Properties:

    1. server.port=8081
    2. spring.datasource.driverClassName=com.mysql.jdbc.Driver
    3. spring.datasource.url=jdbc:mysql://121.196.166.2:3306/microservice
    4. spring.datasource.username=root
    5. spring.datasource.password=root
    6. #logging7
    7. logging.level.com.example.hellospringboot=debug

     使用YAML:

    1. #DB configuration
    2. spring:
    3. datasource:
    4. driver-class-name: com.mysql.jdbc.Driver
    5. url: jdbc:mysql://localhost:3306/microservice
    6. username: root
    7. password: root
    8. #Logging
    9. logging:
    10. level:
    11. com.example.hellospringboot: debug

    从上述配置文件中可以看出,yml文件是一个树状结构的配置,它与properties文件相比,有很大的不同,在编写时需要注意以下几点:

    (1)在properties文件中是以“.”进行分割的,在yml中是用“:”进行分割的。

    (2)yml的数据格式和json的格式很像,都是KV格式,并且通过“:”进行赋值。

    (3)每个key的冒号后面一定都要加一个空格,例如driver-class-name后面的“:”之后,需要有一个空格,否则文件会报错。

    怎么选择?

    由于在SpringBoot官方文档中,主要使用的是properties文件,而SpringCloud官网文档以及一些开源的项目中,大多数使用的是yml文件,这点一开始就要注意,由于Spring Cloud 用的比较多, 因此建议即使在Springboot 项目中,也推荐使用YAML格式,以便于代码风格一致。

    另外,在使用IDEA编辑器时, 同时打开Spring Boot DevTools, 编辑YAML 文件的时候, 提示比较及时,按照提示选择的话,不仅输入量减少了,而且还不容易出错。

  • 相关阅读:
    [附源码]JAVA毕业设计衡师社团管理系统(系统+LW)
    113-JavaSE基础进阶:补充知识-工厂模式、装饰模式
    菜单栏-JS防抖
    性能监控-grafana+prometheus+node_exporter
    计组中的各种周期辨析
    Mybatis 动态 SQL
    【动态代理】
    EMS | 快递单号查询API
    反射...
    Java设计模式面试题及答案(持续更新。。。)
  • 原文地址:https://blog.csdn.net/hintcnuie/article/details/127123720