springboot2.0在application.yml文件中添加自定义配置


1. 在application.yml文件中添加自定义配置

app:
  platform:
    version:
      code: '1.0.0'

2. 定义bean类

具体格式:

  1. 其中的成员变量名称需要与配置的自定义参数名称一致
  2. 每个成员变量必须要有 get/set 方法
  3. 该类使用注解 @Component@ConfigurationProperties 修饰
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author john
 * @date 2019/12/19 - 9:26
 */
@Component
@ConfigurationProperties(prefix="app.platform.version")
public class Version {

    private String code;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    @Override
    public String toString() {
        return "Version{" +
                "code='" + code + '\'' +
                '}';
    }
}

3. 在需要使用的地方使用 @Autowired 注解,自动注入来使用

   @Autowired
    Version version;

4. 测试

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class VersionApplicationTests {
    @Autowired
    Version version;

    @Test
    void testVersion(){
        System.out.println(version.toString());
    }

}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM