有时候我们需要一些全局的常量进行配置,除了定义为全局常量外还可以通过读取配置的方式进行动态修改

    application.yaml

    1. jili:
    2. weixin:
    3. appId: wx00001
    4. appSecret: abbcccccc
    5. push:
    6. badge: 1
    7. sound: default

    Myproperties.java

    1. package com.jili.redistest.config;
    2. import lombok.Data;
    3. import org.springframework.boot.context.properties.ConfigurationProperties;
    4. import org.springframework.stereotype.Component;
    5. /**
    6. * @author: Jili
    7. * @date: Created on 2021/7/12 11:17
    8. */
    9. @Data
    10. @Component
    11. @ConfigurationProperties(prefix = "jili",ignoreUnknownFields = false)
    12. public class Myproperties {
    13. private final Weixin weixin= new Weixin();
    14. private final Push push = new Push();
    15. @Data
    16. public static class Weixin{
    17. private String appId;
    18. private String appSecret;
    19. }
    20. @Data
    21. public static class Push{
    22. private String badge;
    23. private String sound;
    24. }
    25. }
    • ignoreUnknownFields = false 告诉 Spring Boot 在有属性不能匹配到声明的域的时候抛出异常
    • prefix 用来选择哪个属性的prefix名字来绑定

    test.java

    1. @Test
    2. void test1(){
    3. System.out.println(myproperties.getWeixin().getAppId());
    4. myproperties.getWeixin().setAppId("123456");
    5. System.out.println(myproperties.getWeixin().getAppId());
    6. }
    1. wx00001
    2. 123456