【自学记录】SpringBoot+IDEA+Maven(二)

来源:互联网 发布:c罗皇马 知乎 编辑:程序博客网 时间:2024/06/07 10:05

我的第二篇SpringBoot学习笔记

我的开发环境:

  • macOS 10.12.6
  • Intelij IDEA 2017.1
  • java version 1.8.0_144
  • Apache Maven 3.5.0

SpringBoot的属性配置文件application.properties

SpringBoot的项目运行的时候,默认会读取application.properties中的属性,并将这些属性加载到当前环境中。

那么,我来举个栗子。
application.properties的内容如下:

demo.author=usually
demo.lastModifyTime=2017-09-02
demo.createTime=2017-09-01
demo.author.firstName=Usually
demo.author.lastName=Leo
#注意,properties文件中字符串的拼接不是用加号,直接粗暴的写一起就好了
demo.author=${demo.author.firstName} ${demo.author.lastName}
demo.lastModifyTime=2017-09-02
demo.createTime=2017-09-01
#改启动的端口
server.port=8091

我们如何来使用这些属性?

package com.example.demo;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * Created by usually on 2017/9/2. */@RestControllerpublic class PropertiesController {    @Value("${demo.author}")    private String author;    @Value("${demo.createTime}")    private String createTime;    @RequestMapping("/properties")    public String show(){        return this.author+" created this demo at "+this.createTime;    }}

接下来便是见证奇迹的时刻
这里写图片描述


学会了上面这个配置文件的使用方法,接下来这个大招你会更心水
SpringBoot可以包含多个属性配置文件,读取的规则很简单:

首先读取application.properties。如果你的application.properties中有spring.profiles.active=xxx,那么读取完默认属性配置文件之后,接下来读取application-xxx.properties文件。

这样一来,你可以在项目中放多个环境的配置文件,共同的属性放在默认属性配置文件里,每个环境特有的属性放在相应的配置文件中,通过切换spring.profiles.active的值来让相应的属性文件生效,达到切换环境的效果


此外,SpringBoot还支持配置文件产生随机数,我这么说你可能不太明白,还是看下面的代码吧

#random.value可以生成随机的字符串,
generate.code=${random.value}

#random.int和random.long,就是随机的int值和long值

#random.int(n)就是n以内的int值
generate.number=${random.int(n)}

#random.int[n,m]就是n和m之间的int值
generate.password=${random.int[n,m]}

The End