spring boot中读取配置信息一

2019-11-18 23:18:49

一.application.yml文件


yml文件部分 start


01、首先我们都知道一个常识,那就是每个人都有自己的年龄,比如我们现在的业务需求是查询所有年龄大于20的人的相关信息,如果我们选择通过配置文件来配置这个值为20的常量的话,我们该如何配置和如何从配置文件中获取这个值呢?,application.yml的内容如下(注意 “age:“ 和 “20“ 之间需要一个空格,yml的语法 ):



server:  

  port: 8087  

  context-path: /springboot-yml-properties  

  

#年龄   

age: 20  

再controller文件中获取的方式:



   @Value("${age}")  

    private Integer age;  

下面是一个yml配置文件的灵活使用方法:



#年龄   

age: 20  

#姓  

lastName: 王  

content: "age: ${age}, lastName: ${lastName}"  

controller层数据获取:


 @Value("${age}")  

    private Integer age;  

      

    @Value("${lastName}")  

    private String lastName;  

      

    @Value("${content}")  

    private String content;  

  

    @RequestMapping("/test")  

    public String test() {  

        return content;  

    }  

多层:


#人  

person:  

  age: 20  

  lastName: 王  

  date: 2001-03-27 

controller层代码表示:


 @Value("${person.age}")  

    private Integer age;  

二、不同环境的配置dev,uat,prod


新建三个yml文件,分别为application-dev.yml,application-uat.yml,application-prod.yml.三个文件大同小异,dev为开发环境,uat为测试环境,prod为生产环境。application.yml文件根据不同环境改变profiles:active的值,使用不同的文件。


项目启动时可以添加java -jar web.jar spring.profiles.active=uat 来启动不同环境配置,但仅限于开发和测试环境,线上环境不允许这样操作。


dev配置如下


[html] view plain copy

server:  

  port: 8080  

  tomcat:  

    uri-encoding: utf-8  

spring:  

  thymeleaf:  

    mode: LEGACYHTML5  

    cache: false  

  jackson:  

    time-zone: GMT+8  

    date-format: yyyy-MM-dd HH:mm:ss  

  profiles:  

    active: dev  

  http:  

    multipart:  

      max-file-size: 30Mb  

      max-request-size: 30Mb  

  devtools:  

    restart:  

      enabled: true  

mybatis:   

  configuration:  

    map-underscore-to-camel-case: true  

  mapper-locations: mybatis/**/*Mapper.xml  

三、注意


1.spring只能出现一个


2.格式正确,同级要对齐


3.参数的写法:例如age: 20,冒号后面必须有空格否则会报错,idea编译器中会有提醒,eclipse并没有


4.编辑yml文件时不能使用TAB键来缩进,否则启动会报错。



  • 2017-02-10 15:19:51

    Git:代码冲突常见解决方法

    如果系统中有一些配置文件在服务器上做了配置修改,然后后续开发又新添加一些配置项的时候, 在发布这个配置文件的时候,会发生代码冲突:

  • 2017-02-10 15:24:14

    linux学习之——vim简明教程

    学习 vim 并且其会成为你最后一个使用的文本编辑器。没有比这个更好的文本编辑器了,非常地难学,但是却不可思议地好用。 我建议下面这四个步骤: 存活 感觉良好 觉得更好,更强,更快 使用VIM的超能力

  • 2017-02-10 16:22:13

    git历史记录查询

    查看提交历史:git log 查看提交历史并显示版本间的差异:git log -p 查看指定历史:git log xxx(sha1值) -p 查看提交历史(指定时间):

  • 2017-02-13 17:50:05

    cURL error 60: SSL certificate problem: unable to get local issuer certificate

    Drupal 8 version uses Guzzle Http Client internally, but under the hood it may use cURL or PHP internals. If you installed PHP cURL on your PHP server it typically uses cURL and you may see an exception with error Peer certificate cannot be authenticated with known CA certificates or error code CURLE_SSL_CACERT (60).