---
title: "SpringBoot自定义YAML配置类"
author: "buddie"
date: "2018-11-17T16:45:25Z"
tags: []
categories: ["编程语言"]
slug: "springboot-yaml"
draft: false
lastmod: "2018-11-17T16:45:25Z"
id: 2433962
url: "https://buddie.iteye.com/blog/2433962"
---

在开发SpringBoot应用程序中，可以使用yaml文件来配置各种属性及参数，并可以直接映射到Java类的属性当中。

比如，我有一个Java类 UserProperties.java

```
package cn.buddie.test.yaml;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 用户配置
 */
public class UserProperties {
    /**
     * 名称
     */
    private String userName;
    /**
     * 性别
     */
    private int gender;

    // getter & setter
    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setGender(int gender) {
        this.gender = gender;
    }

    public String getUserName() {
        return userName;
    }

    public int getGender() {
        return gender;
    }
}
```

 

 我期望能在yaml文件中配置UserProperties中的属性，当我需要使用时，直接从UserProperties类中取就可以了。

 

只需要给UserProperties类中加入两个注解就可以了

 

```
@ConfigurationProperties("user")
@Component
public class UserProperties
```

 

 

其中@ConfigurationProperties表示这是一个注解类，"user"：表示要解析yaml文件中user开头的配置

@Component表示要将此类做作一个组件，注册到Spring容器中，方便我们的后面通过自动注入来使用。

然后yaml配置文件中，对UserProperties中的属性通过配置就可以

application.yaml

```
user:
  user-name: 'zhangsan'
  gender: 2
```

在java类中属性userName,在yaml中，也可以写成‘user-name’,规则就是把大写字母为成'-'+对应的小写字母 

 

写一个测试类，测试一下

 

 

```
package cn.buddie.test.yaml;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.boot.test.context.SpringBootTest;

@RunWith(SpringRunner.class)
@SpringBootTest
public class YamlTest {

    @Autowired
    private UserProperties userProperties;

    @Test
    public void testYaml() {
        System.out.println(userProperties.getUserName() + "-" + userProperties.getGender());
    }
}
```

 

测试结果

zhangsan-2

 

需要注意的地方

1、需要依赖jar包：

```
compileOnly("org.springframework.boot:spring-boot-configuration-processor")
```

2、属性不能直接用'name'，这样会取到系统环境中的'name'

3、被@ConfigurationProperties注解的配置类，不能为内部类