yml文件基础及springboot中yml文件常见错误

前言:

当下的springboot项目中进行基础信息配置除了使用.properties外,springboot还支持 yml格式。(您要是喜欢直接写在代码中也行)

最常见的还是yml格式的配置,今天记录下yml文件的如何配置以及在配置过程中遇见的问题

一、数据格式写法:

 格式是在yml文件中以“.”分割的属性名称,该为“: ”和换行。

放个例子大家感受下

//properties格式

spring.datasource.username=root
spring.datasource.password: 123
spring.datasource.url: jdbc:mysql://localhost:3306/ge_data?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC

//yml格式

#mysql

spring:
  datasource:
    username: root
    password: 123
    url: jdbc:mysql://localhost:3306/data?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC

 注意:

    1、在配置文件中的注解格式是   #注解

    2、在spring与dataSource是相差两个字母的。(上一级与下一级之间必须是递进关系:表现为差两个字母)

    3、在属性与值之间有一个冒号和空格,并不是冒号之后直接书写。

        4、application.properties 和 application.yml二选一,不要都用,不要折磨Springboot和自己

二、配置后如何取值

1、普通取值 使用 @Value()这个注解

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
    String value();
}

例:

@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;

2、如果是pojo对象呢? 使用@ConfigurationProperties 这个注解,最好指定前缀(在yml文件中的层级)

例:

yml中配置一下

user:
  username: zwr
  age: 23
  id: 1

实体类(指定前缀)

 @ConfigurationProperties(prefix = "user")
    @Data
    public class User {
  private String username;
  private Integer age;
  private Integer id;
    }

    使用

    @RestController
    @EnableConfigurationProperties({User.class})
    public class Yml {
 @Autowired
  User user;
  @RequestMapping("/admin")
  public String getUser(){
    return user.toString();
  }
    }

三、配置可能出现的问题

1、 mapping values are not allowed here
 原因:属性与值之间除了冒号还有一个空格,空格,仔细检查下是不是没打空格,
例:没有空格idea中它都变色了


2、Could not resolve placeholder 'spring.redis.host' in value "${spring.redis.host}
原因:极大原因是因为层级关系不对而导致的
例:正常的层级关系

yml文件基础及springboot中yml文件常见错误_第1张图片
不正常的层级关系

yml文件基础及springboot中yml文件常见错误_第2张图片
3、 while parsing a block mapping
原因:和错误2出现的原因差不多,层级关系不对,导致了解析异常


4、 while scanning for the next token found character '\t(TAB)

原因:缩进有问题,说白了层级关系不对 

解决方法:哪行出错了就缩进哪行,敲几下空格试试,保证层级正常

注意我在上面标红的地方,yml配置中使用Tab来缩进确实不符合yml的语法规则,

5、解析文件层级不是自己想要的层级(解决错误4出现的该问题)

笔者出现的问题5的情况如下 标注的地方不对,但是缩进正确的话pool不会被解析为redis.pool

yml文件基础及springboot中yml文件常见错误_第3张图片

指定redis.pool后正常解析

yml文件基础及springboot中yml文件常见错误_第4张图片

6、name of an alias node must contain at least one character 

例:

yml文件基础及springboot中yml文件常见错误_第5张图片

属性量不是数字需要加单引号

 

肉眼很难检测自己配置哪出了问题,建议大家使用在线校验工具校验

https://www.bejson.com/validators/yaml_editor/
 

你可能感兴趣的:(spring)