SpringBoot custom YAML configuration class

In the development of spring boot applications, you can use yaml files to configure various properties and parameters, and directly map them to the properties of Java classes.

For example, I have a Java class UserProperties.java

package cn.buddie.test.yaml;

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

/**
 * User configuration
 */
public class UserProperties {
    /**
     * Name
     */
    private String userName;
    /**
     * Gender
     */
    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;
    }
}

I expect to be able to configure the properties in UserProperties in yaml file. When I need to use it, I can take it directly from UserProperties class.

 

Just add two annotations to the UserProperties class

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

Where @ ConfigurationProperties indicates that this is an annotation class, and "user": indicates the configuration beginning with user in yaml file to be resolved

@Component means to make this class a component and register it in the Spring container for our later use through automatic injection.

Then in yaml configuration file, you can configure the properties in UserProperties

application.yaml

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

In the java class, the attribute user name can also be written as "user name" in yaml. The rule is to change the upper case letter into the lower case letter corresponding to '-' +

 

Write a test class and test it

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());
    }
}

test result

zhangsan-2

 

What to pay attention to

1. Need to rely on jar package:

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

2. The attribute cannot use 'name' directly, which will get 'name' in the system environment

3. The configuration class annotated by @ ConfigurationProperties cannot be an internal class

Tags: Programming Java Spring Attribute Junit

Posted on Sat, 07 Dec 2019 01:43:18 -0500 by turtleman8605