SpringBoot学习笔记二:配置文件详解

SpringBoot全局配置文件默认为src/main/resources下的application.properties,另外它还可以重命名为.yml格式(即SpringBoot对着两种格式均支持)。

修改默认配置

如修改SpringBoot内嵌Tomcat的启动端口为9080(.yml格式)

server:
  port: 9080

启动项目即可在控制台启动日志中看到

2018-06-24 17:42:25.784  INFO 2658 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 9080 (http) with context path ''

这时在浏览器输入localhost:9080即可正常访问
Spring Boot 全部配置项 SpringBoot Common application properties

自定义属性配置

我们也可以在SpringBoot配置文件中自定义属性配置,如

com:
  example:
    girl:
      name: baby
      age: 18
      cupSize: B

然后通过@Value("${属性名}")注解来加载对应的配置属性
com/example/springbootconfiguration/controller/GirlController.java

package com.example.springbootconfiguration.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GirlController {

    @Value("${com.example.girl.name}")
    private String girlName;

    @Value("${com.example.girl.age}")
    private Integer girlAge;

    @Value("${com.example.girl.cupSize}")
    private String girlCupSize;

    @GetMapping("/girl")
    public String getGirlInfo() {
        return "girlName: " + girlName + " girlAge: " + girlAge + " girlCupSize: " + girlCupSize;
    }

}

启动工程,访问:localhost:9080/girl,浏览器显示:

girlName: baby girlAge: 18 girlCupSize: B

属性注入成功

属性配置间的引用

在SpringBoot全局配置文件中的各个属性之间可以通过直接引用来使用

com:
  example:
    girl:
      name: baby
      age: 18
      cupSize: B
      desc: name:${com.example.girl.name} age:${com.example.girl.age} cupSize:${com.example.girl.cupSize}

同样可以使用@Value注解将girl.desc属性配置注入到某一属性中,如

package com.example.springbootconfiguration.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GirlController {

    @Value("${com.example.girl.name}")
    private String girlName;

    @Value("${com.example.girl.age}")
    private Integer girlAge;

    @Value("${com.example.girl.cupSize}")
    private String girlCupSize;

    @Value("${com.example.girl.desc}")
    private String girlDesc;

    @GetMapping("/girl")
    public String getGirlInfo() {
        // return "girlName: " + girlName + " girlAge: " + girlAge + " girlCupSize: " + girlCupSize;
        return girlDesc;
    }

}

再次启动工程,访问:localhost:9080/girl,浏览器显示:

name:baby age:18 cupSize:B

将属性配置赋给实体类

当我们属性配置很多的时候,使用@Value注解一个一个的注入将会变得很繁琐,这时SpringBoot提供了将属性配置与实体类结合的方式,具体先来看一下SpringBoot中官方的使用如org.springframework.boot.autoconfigure.data.redis.RedisProperties

package org.springframework.boot.autoconfigure.data.redis;

import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(
    prefix = "spring.redis"
)
public class RedisProperties {
    private int database = 0;
    private String url;
    private String host = "localhost";
    private String password;
    private int port = 6379;
    private boolean ssl;
    private int timeout;
    private RedisProperties.Pool pool;
    private RedisProperties.Sentinel sentinel;
    private RedisProperties.Cluster cluster;
    
    ...
}

对于上面我们自己关于girl的一些配置,同理我们可以创建一个GirlProperties类,如

package com.example.springbootconfiguration.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;

@Component
@ConfigurationProperties(prefix = "com.example.girl")
public class GirlProperties {

    private String name;

    private Integer age;

    private String cupSize;
    // ... getter and setters
}

当你在Idea中敲完这些代码Idea可能会提示Spring Boot Configuration Annotation Processor not found in classpath

Spring Boot Configuration Annotation Processor not found提示

点击Open Documentation会打开Generating Your Own Metadata by Using the Annotation Processor页面
嗯,主要是少了个依赖spring-boot-configuration-processor

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

如何使用?在需要使用的类上加@EnableConfigurationProperties注解,同时使用@Autowired注解注入即可,如

package com.example.springbootconfiguration.controller;

import com.example.springbootconfiguration.properties.GirlProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableConfigurationProperties(value = {GirlProperties.class})
public class GirlController {

    @Autowired
    private GirlProperties girlProperties;

    @GetMapping("/girl2")
    public GirlProperties getGirlInfo2() {
        return girlProperties;
    }

}

再次启动工程,访问:localhost:9080/girl2,浏览器显示:


返回结果

使用随机值

Spring Boot的属性配置文件中可以通过${random}来产生随机int、long、uuid或者string字符串,来支持属性的随机值。

${random}随机值

比如我们给girl随机来个年龄

age: ${random.int}

自定义配置文件

虽然SprinBoot提供了application.properties或application.yml全局配置文件,但有时我们还是需要自定义配置文件,如将上文关于girl的属性配置提取到girl.properties文件中

girl.name: baby
girl.age: 18
girl.cupSize: B

GirlProperties2.java

package com.example.springbootconfiguration.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:girl.properties")
@ConfigurationProperties(prefix = "girl")
public class GirlProperties2 {

    private String name;

    private Integer age;

    private String cupSize;

}

GirlController.java

package com.example.springbootconfiguration.controller;

import com.example.springbootconfiguration.properties.GirlProperties;
import com.example.springbootconfiguration.properties.GirlProperties2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableConfigurationProperties(value = {GirlProperties.class, GirlProperties2.class})
public class GirlController {

    @Autowired
    private GirlProperties2 girlProperties2;

    @GetMapping("/girl3")
    public GirlProperties2 getGirlInfo3() {
        return girlProperties2;
    }

}

再次启动工程,访问:localhost:9080/girl3,浏览器显示:


返回结果

多环境配置

实际开发中可能会有不同的环境,有开发环境、测试环境、生成环境。对于每个环境相关配置都可能有所不同,如:数据库信息、端口配置、本地路径配置等。

如果每次切换不同环境都需要修改application.properties,那么操作是十分繁琐的。在spring boot中提供了多环境配置,使得我们切换环境变得简便。

在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:

  • application-test.yml:测试环境
server:
  servlet:
    context-path: /test
  • application-dev.yml:开发环境
server:
  servlet:
    context-path: /dev
  • application-prod.yml:生产环境
server:
  servlet:
    context-path: /prod

激活profile,在application.yml文件中通过spring.profiles.active属性来设置,其值对应{profile}值,如

spring:
  profiles:
    active: dev

这时启动应用访问localhost:9080/girl3就访问不到了,需访问localhost:9080/dev/girl3才行

用命令运行jar包启动应用的时候,可以指定相应的配置.

mvn package
java -jar target/spring-boot-configuration-0.0.1-SNAPSHOT.jar --spring.profiles..active=dev 

注:命令行参数这种jar包指定参数启动应用的方式,可能是不安全的,我们可以在启动类中设置禁止这种方式启动应用,如下:

package com.example.springbootconfiguration;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;

@SpringBootApplication
public class SpringBootConfigurationApplication {

    public static void main(String[] args) {
        // SpringApplication.run(SpringBootConfigurationApplication.class, args);
        SpringApplication application = new SpringApplication(SpringBootConfigurationApplication.class);
        application.setAddCommandLineProperties(false);
        application.run(args);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容