• spring boot 获取配置文件的值


    1.yaml形式配置

    1.yaml

      Persion:
            name: 张三
            age: 18
            birthday: 2017/8/21
            pets: {name: dog,age: 2}
            frients: [lisi,wangwu,zhaoliu]

    2.java

    在需要使用读取yaml配置文件中的值的时候需要添加@configurationproperties 注解prefix标记了需要读取配置文件中那个那个配置下的属性进行一一映射

     @Data
        @ConfigurationProperties(prefix = "Persion")
        @Component
        public class Persion implements Serializable {
            public String name;
            public int age;
            public Date birthday;
            public Map<String,Object> pets;
            public List<String> frients;
        }
    
        @Data
        public class Pet implements Serializable {
            public String name;
            public Integer age;
        }

    如果不使用@configurationproperties注解系统会报

    SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

    如果不添加prefix属性时,获取的属性值都为null

    在包装map类型时,map的值如果为对象,需要使用Object或者?标识,不然系统会报系统无法转换错误

    3.controller

        @Controller
        public class Test {
    
            @Autowired
            private Persion persion;
    
            @RequestMapping("/sayHello")
            @ResponseBody
            public Persion sayHello(){
                return persion;
            }
        }

    4.pom文件

    需要读取yaml配置文件中的值时需要在pom文件中添加配置文件解析器,该解析器的作用是将配置文件中的值和标记了@configurationproperties的类的属性进行对应映射

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

    2.properties形式配置

     server.port=8082
        Persion.age=12
        Persion.birthday=207/12/12
        Persion.frients=a,c,v
        Persion.name=李四
        Persion.pets.name="dog"
        Persion.pets.age=3

    在properties配置文件中使用中文时需要进行设置,idea需要在读取时将文件转码,在file->setting->editor->file encodings下把transparent native-to-ascll conversion勾选上就行了。

  • 相关阅读:
    【BZOJ 1185】 凸包+旋转卡壳
    【BZOJ 2829】 2829: 信用卡凸包 (凸包)
    【BZOJ 1045】 1045: [HAOI2008] 糖果传递
    【BZOJ 2453|bzoj 2120】 2453: 维护队列 (分块+二分)
    【BZOJ 3343 】 分块
    【BZOJ 1069】 凸包+旋转卡壳
    【NOIP 2016 总结】
    【无聊放个模板系列】洛谷 负环 模板
    【无聊放个模板系列】BZOJ 3172 (AC自动机)
    【无聊放个模板系列】HDU 3506 (四边形不等式优化DP-经典石子合并问题[环形])
  • 原文地址:https://www.cnblogs.com/fanxl/p/9123015.html
Copyright © 2020-2023  润新知