简介

在早前的博客中曾经写过 Spring 程序通过 Bean 映射实现配置信息的读取。

在SpringBoot 框架中读取配置的方式变得非常多样,这导致读者在搜寻资料时反而容易迷糊。

  • 到底,SpringBoot 是按什么顺序加载配置?
  • 相应的,我们该选择什么样的方式去读取?

一、配置样例

先看一个例子:

@Compoment
public class BuildConfig{ @Value("${buildinfo.version")
private String version; ...
}

代码中,@Component 将 BuildConfig 注册为 Bean ,

接下来使用 @Value 注解,将 配置中的 buildinfo.version键映射到了 version 字段上。

我们都知道,通过 application.properties 可以方便的配置一些属性。

属性的值是支持变量替换的,如下:

myName=Lilei
myDesc=${myName} is a good man

这点,是由 SpringBoot 自动生成的 PropertyPlaceholderConfigurer 对象实现的。

除了 上面所说 application.properties 之外,还有什么途径?

下面介绍如何注入配置

二、如何注入配置

1. 缺省配置文件

类路径中 application.properties(yml) 是默认的配置文件。

此外如果启动应用时,当前目录中存在同名的配置文件,则以此优先。

在此规则之下,SpringBoot 还能识别不同 profile下的配置,这将在后面篇幅中介绍。

2. 使用注解

@PropertySource

可指定属性配置文件的位置,

样例代码:

@Configuration

@PropertySource("classpath:/com/myco/app.properties")

public class AppConfig {

     @Autowired

     Environment env;

     @Bean

     public TestBean testBean() {

         TestBean testBean = new TestBean();

         testBean.setName(env.getProperty("testbean.name"));

         return testBean;

     }

}

@TestPropertySource

与 @PropertySource 类似,该注解用于指定测试环境中的属性文件,其优先级高于 @PropertySource。

3. 启动参数

以下的命令以指定参数启动 SpringBoot 应用

java -jar application.jar --server.port=9000

server.port 值将被注入为环境属性值。

而以下的命令还可以指定 配置文件的位置

java -jar application.jar --spring.config.location=/etc/xxx.properties

这个spring.config.location就是指的配置文件位置,

默认情况下,SpringBoot 会从下面几路径找到配置文件:

路径
file:./config/
file:./
classpath:/config/
classpath:/

还有..

SpringBoot 注入配置的方式其实非常多,完整顺序如下表:

优先级 配置
1 @TestPropertySource 注解
2 @SpringBootTest 注解
3 命令行参数
4 SPRING_APPLICATION_JSON 属性值(或环境变量)
5 Servlet 相关参数
6 JNDI 属性
7 Java 系统属性 (System.getProperties())
8 操作系统环境变量
9 RandomValuePropertySource 随机属性
10 Jar包外部 application-{profile}.properties
11 Jar包内部 application-{profile}.properties
12 Jar包外部 application.properties
13 Jar包内部 application.properties
14 @PropertySource 注解
15 SpringApplication 默认值

三、如何读取配置

@Value 注解

如以下的实现:

@Configuration
public class AppConfig { @Value("${api.log.enabled:false}")
private boolean apiLogEnabled;

除了类型自动转换之外,通过:false后缀可以指定默认值。

Environment 接口

Environment 是一个类似 Properties 的接口,用来获取属性非常方便。

@Configuration
public class AppConfig { @Autowired
private Environment environment; public String getApplicationId() {
return this.environment.getProperty("application.id");
}
}

@ConfigurationProperties 注解

该注解一般用作前缀匹配,下面的代码摘自Mongodb

@ConfigurationProperties(prefix = "spring.data.mongodb")
public class MongoProperties { /**
* Mongo server host.
*/
private String host; /**
* Mongo server port.
*/
private Integer port = null; /**
* Database name.
*/
private String database;

相应的 Mongodb 配置信息如:

spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=xxx

四、不同环境中的配置

Spring 提供了 Profile 机制用于管理不同环境的配置。

配置内容可以是 Java Config(对应@Component或@Configuration),也可以是配置文件。

如:

@Configuration
@Profile("prod")
public class ProdConfiguration { // ... }

通过@Profile注解可将代码配置关联到某个配置环境

在具体应用中,Profile的用途通常有二:

1. 区别开发、测试、发布环境

对于dev、prod、test分别做不同的配置

//for dev
application-dev.properties //for prod
application-prod.properties //for test
application-test.properties

可以在 application.properties 指定启用的环境:

spring.profiles.active=dev

也可以通过命令行指定:

java -jar app.jar --spring.profiles.active=prod

2. 声明多配置文件

当内容过多时,可以将配置信息进行拆分,如下:

application-mongodb.properties

spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.username=xxx
spring.data.mongodb.password=xxx
spring.data.mongodb.database=xxx

application-mail.properties

spring.mail.host=xxx
spring.mail.username=xxx
spring.mail.password=xxx spring.mail.from=xxx
spring.mail.to=xxx
spring.mail.cc=xxx

在主配置文件指定包含关系:

application.properties

spring.profiles.include=mongodb,mail

参考文档

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

欢迎继续关注"美码师的补习系列-springboot篇" ,如果觉得老司机的文章还不赖,请多多分享转发-

补习系列(10)-springboot 之配置读取的更多相关文章

  1. 补习系列(14)-springboot redis 整合-数据读写

    目录 一.简介 二.SpringBoot Redis 读写 A. 引入 spring-data-redis B. 序列化 C. 读写样例 三.方法级缓存 四.连接池 小结 一.简介 在 补习系列(A3 ...

  2. 补习系列(15)-springboot 分布式会话原理

    目录 一.背景 二.SpringBoot 分布式会话 三.样例程序 四.原理进阶 A. 序列化 B. 会话代理 C. 数据老化 小结 一.背景 在 补习系列(3)-springboot 几种scope ...

  3. 源码学习系列之SpringBoot自动配置(篇二)

    源码学习系列之SpringBoot自动配置(篇二)之HttpEncodingAutoConfiguration 源码分析 继上一篇博客源码学习系列之SpringBoot自动配置(篇一)之后,本博客继续 ...

  4. 源码学习系列之SpringBoot自动配置(篇一)

    源码学习系列之SpringBoot自动配置源码学习(篇一) ok,本博客尝试跟一下Springboot的自动配置源码,做一下笔记记录,自动配置是Springboot的一个很关键的特性,也容易被忽略的属 ...

  5. 补习系列(16)-springboot mongodb 数据库应用技巧

    目录 一.关于 MongoDB 二.Spring-Data-Mongo 三.整合 MongoDB CRUD A. 引入框架 B. 数据库配置 C. 数据模型 D. 数据操作 E. 自定义操作 四.高级 ...

  6. 补习系列(19)-springboot JPA + PostGreSQL

    目录 SpringBoot 整合 PostGreSQL 一.PostGreSQL简介 二.关于 SpringDataJPA 三.整合 PostGreSQL A. 依赖包 B. 配置文件 C. 模型定义 ...

  7. 补习系列(18)-springboot H2 迷你数据库

    目录 关于 H2 一.H2 用作本地数据库 1. 引入依赖: 2. 配置文件 3. 样例数据 二.H2 用于单元测试 1. 依赖包 2. 测试配置 3. 测试代码 小结 关于 H2 H2 数据库是一个 ...

  8. 补习系列(17)-springboot mongodb 内嵌数据库

    目录 简介 一.使用 flapdoodle.embed.mongo A. 引入依赖 B. 准备测试类 C. 完善配置 D. 启动测试 细节 二.使用Fongo A. 引入框架 B. 准备测试类 C.业 ...

  9. 补习系列(13)-springboot redis 与发布订阅

    目录 一.订阅发布 常见应用 二.Redis 与订阅发布 三.SpringBoot 与订阅发布 A. 消息模型 B. 序列化 C. 发布消息 D. 接收消息 小结 一.订阅发布 订阅发布是一种常见的设 ...

随机推荐

  1. teamviewer quicksupport 插件(下载)

    teamviewer quicksupport 插件(下载) teamviewer是一款远程控制软件(免费,比较好的); teamviewer quicksupport是一款支持手机可以被远程控制软件 ...

  2. IOS开发中将定时器添加到runLoop中

    runLoop主要就是为线程而生的.他能够让线程在有任务的时候保持工作状态,没有任务的时候让线程处于休眠待备状态. 主线程的runloop默认是开启的.主线程上创建的定时器已经默认添加到runLoop ...

  3. org.hibernate.hql.internal.ast.QuerySyntaxException: XXX is not mapped

    异常情况: 最近在把一个项目拆分多个 module 的时候数据库查询遇到这个异常:org.hibernate.hql.internal.ast.QuerySyntaxException: Identi ...

  4. rest_framework之认证源码剖析

    如果我们写API有人能访问,有人不能访问,则需要些认证. 如何知道该用户是否已登入? 如果用户登入成功,则给用户一个随机字符串,去访问另一个页面. 以前写session的时候,都是把session写c ...

  5. 3.1circle

    就是括号匹配的题目,如果有交集就是NO #include<iostream> #include<cstring> #include<stdio.h> #includ ...

  6. 通过cmd命令,杀掉占用端口号的进程

    错误问题:[Error running public: Unable to open debugger port (127.0.0.1:53110): java.net.BindException & ...

  7. 【从零开始搭建自己的.NET Core Api框架】(三)集成轻量级ORM——SqlSugar:3.1 搭建环境

    系列目录 一.  创建项目并集成swagger 1.1 创建 1.2 完善 二. 搭建项目整体架构 三. 集成轻量级ORM框架——SqlSugar 3.1 搭建环境 3.2 实战篇:利用SqlSuga ...

  8. [Java]LeetCode133. 克隆图 | Clone Graph

    Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...

  9. [Bash]LeetCode194. 转置文件 | Transpose File

    Given a text file file.txt, transpose its content. You may assume that each row has the same number ...

  10. [Swift]LeetCode481. 神奇字符串 | Magical String

    A magical string S consists of only '1' and '2' and obeys the following rules: The string S is magic ...