【转载】Spring boot学习记录(二)-配置文件解析
前言:本系列文章非本人原创,转自:http://tengj.top/2017/04/24/springboot0/
正文
Spring Boot使用了一个全局的配置文件application.properties,放在src/main/resources目录下或者类路径的/config下。Sping Boot的全局配置文件的作用是对一些默认配置的配置值进行修改。
注:如果你的工程没有这个application.properties,那就在src/main/resources目录下新建一个。
自定义属性
application.properties提供自定义属性的支持,这样我们就可以把一些常量配置在这里:
com.birdboot.bootDemo.author=one-bird
com.birdboot.bootDemo.dream=world peace
然后直接在要使用的地方通过注解@Value(value=”${config.name}”)就可以绑定到想要的属性上面
package com.birdboot.bootDemo; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
@SpringBootApplication
public class BootDemoApplication { @Value("${com.birdboot.bootDemo.author}")
private String name; @Value("${com.birdboot.bootDemo.dream}")
private String dream; @RequestMapping("/")
public String index(){
return name + " " + dream;
} public static void main(String[] args) {
SpringApplication.run(BootDemoApplication.class, args);
} }
我们启动工程输入http://localhost:8080 就可以看到打印了”one-bird world peace”。
有时候属性太多了,一个个绑定到属性字段上太累,官方提倡绑定一个对象的bean,这里我们建一个ConfigBean.java类,顶部需要使用注解@ConfigurationProperties(prefix = “com.birdboot.bootDemo”)来指明使用哪个
package com.birdboot.module.bean; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "com.birdboot.bootDemo")
public class ConfigBean { private String name;
private String dream; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDream() {
return dream;
}
public void setDream(String dream) {
this.dream = dream;
}
}
这里配置完还需要在spring Boot入口类加上@EnableConfigurationProperties并指明要加载哪个bean,如果不写ConfigBean.class,在bean类那边添加
package com.birdboot.bootDemo; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import com.birdboot.module.bean.ConfigBean; @SpringBootApplication
@EnableConfigurationProperties({ConfigBean.class})
public class BootDemo2Application { public static void main(String[] args) {
SpringApplication.run(BootDemo2Application.class, args);
}
}
最后在Controller中引入ConfigBean使用即可,如下:
package com.birdboot.module.controller; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.birdboot.module.bean.ConfigBean; @RestController
public class UserController { @Autowired
private ConfigBean configBean; @RequestMapping("/")
public String hexo(){
return configBean.getName() + configBean.getDream();
}
}
参数间引用
在application.properties中的各个参数之间也可以直接引用来使用,如下面的设置:
com.birdboot.bootDemo.author=one-bird
com.birdboot.bootDemo.dream=world peace
com.birdboot.bootDemo.line=${com.birdboot.bootDemo.author} hope ${com.birdboot.bootDemo.dream}
这样我们就可以只是用line这个属性就好
使用自定义配置文件
有时候不希望把所有配置都放在application.properties里面,这时候我们可以另外定义一个,这里命名为test.properties,路径跟也放在src/main/resources下面
com.birdboot.bootDemo.author=bird
com.birdboot.bootDemo.dream=house
新建一个bean类,如下:
package com.birdboot.module.bean; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource; @Configuration
@ConfigurationProperties(prefix = "com.birdboot.bootDemo")
@PropertySource("classpath:test.properties")
public class Config2Bean { private String name;
private String dream; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDream() {
return dream;
}
public void setDream(String dream) {
this.dream = dream;
}
}
这里要注意哦,有一个问题,如果你使用的是1.5以前的版本,那么可以通过locations指定properties文件的位置,这样:
@ConfigurationProperties(prefix = "com.birdboot.bootDemo",locations="classpath:test.properties")
但是1.5版本后就没有这个属性了,找了半天发现添加@Configuration和@PropertySource(“classpath:test.properties”)后才可以读取。
随机值配置
配置文件中${random} 可以用来生成各种不同类型的随机值,从而简化了代码生成的麻烦,例如 生成 int 值、long 值或者 string 字符串。
bird.secret=${random.value}
bird.number=${random.int}
bird.bignumber=${random.long}
bird.uuid=${random.uuid}
bird.number.less.than.ten=${random.int(10)}
bird.number.in.range=${random.int[1024,65536]}
外部配置-命令行参数配置
Spring Boot是基于jar包运行的,打成jar包的程序可以直接通过下面命令运行:
java -jar xx.jar
可以以下命令修改tomcat端口号:
java -jar xx.jar --server.port=9090
可以看出,命令行中连续的两个减号--就是对application.properties中的属性值进行赋值的标识。
所以java -jar xx.jar --server.port=9090等价于在application.properties中添加属性server.port=9090。
如果你怕命令行有风险,可以使用SpringApplication.setAddCommandLineProperties(false)禁用它。
实际上,Spring Boot应用程序有多种设置途径,Spring Boot能从多重属性源获得属性,包括如下几种:
- 根目录下的开发工具全局设置属性(当开发工具激活时为
~/.spring-boot-devtools.properties)。 - 测试中的@TestPropertySource注解。
- 测试中的@SpringBootTest#properties注解特性。
- 命令行参数
SPRING_APPLICATION_JSON中的属性(环境变量或系统属性中的内联JSON嵌入)。ServletConfig初始化参数。ServletContext初始化参数。- java:comp/env里的JNDI属性
- JVM系统属性
- 操作系统环境变量
- 随机生成的带random.* 前缀的属性(在设置其他属性时,可以应用他们,比如${random.long})
- 应用程序以外的application.properties或者appliaction.yml文件
- 打包在应用程序内的application.properties或者appliaction.yml文件
- 通过@PropertySource标注的属性源
- 默认属性(通过
SpringApplication.setDefaultProperties指定).
这里列表按组优先级排序,也就是说,任何在高优先级属性源里设置的属性都会覆盖低优先级的相同属性,列如我们上面提到的命令行属性就覆盖了application.properties的属性。
配置文件的优先级
application.properties和application.yml文件可以放在以下四个位置:
- 外置,在相对于应用程序运行目录的/congfig子目录里。
- 外置,在应用程序运行的目录里
- 内置,在config包内
- 内置,在Classpath根目录
同样,这个列表按照优先级排序,也就是说,src/main/resources/config下application.properties覆盖src/main/resources下application.properties中相同的属性,如图:

此外,如果在相同优先级位置同时有application.properties和application.yml,那么application.properties里的属性里面的属性就会覆盖application.yml。
Profile-多环境配置
当应用程序需要部署到不同运行环境时,一些配置细节通常会有所不同,最简单的比如日志,生产日志会将日志级别设置为WARN或更高级别,并将日志写入日志文件,而开发的时候需要日志级别为DEBUG,日志输出到控制台即可。
如果按照以前的做法,就是每次发布的时候替换掉配置文件,这样太麻烦了,Spring Boot的Profile就给我们提供了解决方案,命令带上参数就搞定。
这里我们来模拟一下,只是简单的修改端口来测试
在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:
- application-dev.properties:开发环境
- application-prod.properties:生产环境
想要使用对应的环境,只需要在application.properties中使用spring.profiles.active属性来设置,值对应上面提到的{profile},这里就是指dev、prod这2个。
当然你也可以用命令行启动的时候带上参数:
java -jar xxx.jar --spring.profiles.active=dev
给不同的环境添加不同的端口属性server.port,然后根据指定不同的spring.profiles.active来切换使用。
除了可以用profile的配置文件来分区配置我们的环境变量,在代码里,我们还可以直接用@Profile注解来进行配置,例如数据库配置,这里我们先定义一个接口。
package com.birdboot.module.service;
public interface DBConnector {
public void configure();
}
分别定义俩个实现类来实现它
package com.birdboot.module.service.impl; import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component; import com.birdboot.module.service.DBConnector; /**
* 测试环境
* @author one-bird
*/
@Component
@Profile("testdb")
public class TestDBConnector implements DBConnector { @Override
public void configure() {
System.out.println("testdb");
} }
package com.birdboot.module.service.impl; import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component; import com.birdboot.module.service.DBConnector; /**
* 开发环境
* @author one-bird
*/
@Component
@Profile("devdb")
public class DevDBConnector implements DBConnector { @Override
public void configure() {
System.out.println("devdb");
} }
通过在配置文件激活具体使用哪个实现类
spring.profiles.active=testdb
然后就可以这么用了
package com.birdboot.module.controller; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.birdboot.module.service.DBConnector; @RestController
@RequestMapping("/task")
public class TaskController { @Autowired
DBConnector connector; @RequestMapping(value = {"/",""})
public String hellTask(){
connector.configure(); //最终打印testdb
return "hello task !! myage is ";// + myage;
}
}
除了spring.profiles.active来激活一个或者多个profile之外,还可以用spring.profiles.include来叠加profile
spring.profiles.active: testdb
spring.profiles.include: proddb,prodmq
总结
这次对Spring Boot中application.properties配置文件做的整理总结,希望对大家有所帮助,最后贴上Spring Boot中常用的配置属性,需要的时候可打开查找:
https://www.cnblogs.com/cainiaomahua/p/11609599.html
后记
此处记录本人的一些踩过的坑。
1、Spring boot的启动类存放位置需要放置在controller类的父级文件夹,否则通过网页访问,会报404,如下图:

【转载】Spring boot学习记录(二)-配置文件解析的更多相关文章
- Spring Boot学习记录(二)--thymeleaf模板 - CSDN博客
==他的博客应该不错,没有细看 Spring Boot学习记录(二)--thymeleaf模板 - CSDN博客 http://blog.csdn.net/u012706811/article/det ...
- Spring Boot学习记录(二)–thymeleaf模板
自从来公司后都没用过jsp当界面渲染了,因为前后端分离不是很好,反而模板引擎用的比较多,thymeleaf最大的优势后缀为html,就是只需要浏览器就可以展现页面了,还有就是thymeleaf可以很好 ...
- 我的Spring Boot学习记录(二):Tomcat Server以及Spring MVC的上下文问题
Spring Boot版本: 2.0.0.RELEASE 这里需要引入依赖 spring-boot-starter-web 这里有可能有个人的误解,请抱着怀疑态度看. 建议: 感觉自己也会被绕晕,所以 ...
- 【转载】Spring boot学习记录(三)-启动原理解析
前言:本系列文章非本人原创,转自:http://tengj.top/2017/04/24/springboot0/ 正文 我们开发任何一个Spring Boot项目,都会用到如下的启动类 @Sprin ...
- Spring Boot学习(二):配置文件
目录 前言 方式1:通过配置绑定对象的方式 方式2:@Value("${blog.author}")的形式获取属性值 相关说明 注解@Value的说明 参考 前言 Spring B ...
- 【转载】Spring boot学习记录(一)-入门篇
前言:本系列文章非本人原创,转自:http://tengj.top/2017/04/24/springboot0/ 正文 首先声明,Spring Boot不是一门新技术.从本质上来说,Spring B ...
- Spring Boot学习记录03_一些属性配置文件
转自:http://blog.didispace.com/springbootproperties/ 多环境配置(这个地方跟maven的profile配置有点类似) 我们在开发Spring Boot应 ...
- Spring Boot学习笔记二
Spring Boot入门第二篇 第一天的详见:https://www.cnblogs.com/LBJLAKERS/p/12001253.html 同样是新建一个pring Initializer快速 ...
- Spring Boot学习(三)解析 Spring Boot 项目
一.解析 pom.xml 文件 <?xml version="1.0" encoding="UTF-8"?> <project xmlns=& ...
随机推荐
- TensorFlow——CNN卷积神经网络处理Mnist数据集
CNN卷积神经网络处理Mnist数据集 CNN模型结构: 输入层:Mnist数据集(28*28) 第一层卷积:感受视野5*5,步长为1,卷积核:32个 第一层池化:池化视野2*2,步长为2 第二层卷积 ...
- SQL Server 2008将数据库数据导出到脚本
1.在要到处的数据库上右键 2.选择“任务” 3.选择“生成脚本” 4.选定要导出的数据库 5.在“编写数据的脚本”处选择“True” 6.接下来选定要导出的表,然后选择“完成”
- webpack 4.0 报错
ERROR in multi ./src/entery.js dist/bundle.jsModule not found: Error: Can't resolve 'dist/bundle.js' ...
- CentOS7安装mysql8.0编译报错集合
以下都是我安装mysql8.0遇到的一些报错和解决方法 1.does not appear to contain CMakeLists.txt. 原因:mysql下载的源码包不对 解决方法:下载正确的 ...
- [NOI2004]郁闷的出纳员(平衡树)
[NOI2004]郁闷的出纳员 题目链接 题目描述 OIER公司是一家大型专业化软件公司,有着数以万计的员工.作为一名出纳员,我的任务之一便是统计每位员工的工资.这本来是一份不错的工作,但是令人郁闷的 ...
- NOIP原题板刷
update 10.11 我可能已经刷完大部分了,可是这篇blog我也不想更了 这个人很懒,做了很多题但是不想写题解,也不想更blog,所以这篇blog又咕咕了. 把从 \(1997-2017\) 近 ...
- mysql 乐观锁、悲观锁、共享锁,排它锁
mysql锁机制分为表级锁和行级锁,本文就和大家分享一下我对mysql中行级锁中的共享锁与排他锁进行分享交流. 共享锁又称为读锁,简称S锁,顾名思义,共享锁就是多个事务对于同一数据可以共享一把锁,都能 ...
- php内置函数分析之strtoupper()、strtolower()
strtoupper(): PHP_FUNCTION(strtoupper) { zend_string *str; ZEND_PARSE_PARAMETERS_START(, ) Z_PARAM_S ...
- mysql 注入绕过小特性
1. 注释 Select /*多行(单行)注释*/ version(); Select version(); #单行注释 Select version(); -- 单行注释 (两划线之后必须有空格) ...
- 机器学习:2.NPL自然语言处理
1. 词带的简单解释: 每一个词出现了多少次,缺点是不知道顺序 2.seq2seq自然语言处理的核心 RNN: 一对一:输入一个,输出一个 一对多:输入一个,输出多个 多对一:输入多个,输出一个 多对 ...