zoukankan      html  css  js  c++  java
  • 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勾选上就行了。

  • 相关阅读:
    SED&AWK
    load average[zhuan]
    To be learned
    Android计时器 android.widget.Chronometer
    Play初识
    获取视图的宽高
    自定义摄像机
    Android VideoView使用小记
    在android中,如何去掉webview读取网页后点击网页上的按钮出现的方框
    阿里云主机试用之自建站点和ftp上传所遇的2个问题
  • 原文地址:https://www.cnblogs.com/fanxl/p/9123015.html
Copyright © 2011-2022 走看看