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 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).

  • 2017-02-16 08:09:01

    HTML中PRE和p的区别

    pre 元素可定义预格式化的文本。被包围在 pre 元素中的文本通常会保留空格和换行符。而文本也会呈现为等宽字体。 <pre> 标签的一个常见应用就是用来表示计算机的源代码。

  • 2017-02-16 15:14:14

    动态加载js和css

    开发过程中经常需要动态加载js和css,今天特意总结了一下常用的方法。