前言:本系列文章非本人原创,转自: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学习记录(二)-配置文件解析的更多相关文章

  1. Spring Boot学习记录(二)--thymeleaf模板 - CSDN博客

    ==他的博客应该不错,没有细看 Spring Boot学习记录(二)--thymeleaf模板 - CSDN博客 http://blog.csdn.net/u012706811/article/det ...

  2. Spring Boot学习记录(二)–thymeleaf模板

    自从来公司后都没用过jsp当界面渲染了,因为前后端分离不是很好,反而模板引擎用的比较多,thymeleaf最大的优势后缀为html,就是只需要浏览器就可以展现页面了,还有就是thymeleaf可以很好 ...

  3. 我的Spring Boot学习记录(二):Tomcat Server以及Spring MVC的上下文问题

    Spring Boot版本: 2.0.0.RELEASE 这里需要引入依赖 spring-boot-starter-web 这里有可能有个人的误解,请抱着怀疑态度看. 建议: 感觉自己也会被绕晕,所以 ...

  4. 【转载】Spring boot学习记录(三)-启动原理解析

    前言:本系列文章非本人原创,转自:http://tengj.top/2017/04/24/springboot0/ 正文 我们开发任何一个Spring Boot项目,都会用到如下的启动类 @Sprin ...

  5. Spring Boot学习(二):配置文件

    目录 前言 方式1:通过配置绑定对象的方式 方式2:@Value("${blog.author}")的形式获取属性值 相关说明 注解@Value的说明 参考 前言 Spring B ...

  6. 【转载】Spring boot学习记录(一)-入门篇

    前言:本系列文章非本人原创,转自:http://tengj.top/2017/04/24/springboot0/ 正文 首先声明,Spring Boot不是一门新技术.从本质上来说,Spring B ...

  7. Spring Boot学习记录03_一些属性配置文件

    转自:http://blog.didispace.com/springbootproperties/ 多环境配置(这个地方跟maven的profile配置有点类似) 我们在开发Spring Boot应 ...

  8. Spring Boot学习笔记二

    Spring Boot入门第二篇 第一天的详见:https://www.cnblogs.com/LBJLAKERS/p/12001253.html 同样是新建一个pring Initializer快速 ...

  9. Spring Boot学习(三)解析 Spring Boot 项目

    一.解析 pom.xml 文件 <?xml version="1.0" encoding="UTF-8"?> <project xmlns=& ...

随机推荐

  1. JAVA总结--java基本语法

    static :静态的~ static :静态变量.静态方法: 被修饰的成员变量或者方法独立于该类的任何对象,只要该类被加载,被修饰的成员变量或者方法就存在并可以使用.  用public修饰的stat ...

  2. MySQL-第十三篇使用ResultSetMetaData分析结果集

    1.Result里面包含了一个getMetaData()方法,该方法返回该ResultSet对应的ResultSetMetaData对象. 2.ResultSetMetaData包含的方法: 1> ...

  3. Visual Studio 2017打包安装项目

    在我们用VS编好上位机后,就可以在自己电脑运行上位机,但是想其他人电脑运行上位机可能就行不通了,因为其他人电脑不一定有所需要的运行环境.这时我们就需要打包安装,把运行软件所需要的环境都打包在安装包里. ...

  4. 小白学Python(18)——pyecharts 关系图 Graph

    Graph-基本示例 import json import os from pyecharts import options as opts from pyecharts.charts import ...

  5. CSRF verification failed. Request aborted.错误解决办法

    在Django项目的页面,提交form表单POST请求时,会出现报错:CSRF verification failed. Request aborted. 需要在form表单中加:{% csrf_to ...

  6. 重绘ComboBox —— 让ComboBox多列显示

    最近在维护一个winform项目,公司购买的是DevExpress控件 (请问怎么联系DevExpress工作人员? 我想询问下,广告费是怎么给的.:p),经过公司大牛们对DevExpress控件疯狂 ...

  7. 遍历并读取指定目录下的所有文件内容,写入Map集合然后输出在控制台和本地文件

    public class FileWrite { public static void main(String[] args) throws Exception { //封装数据源目录 File sr ...

  8. linux 修改 rsyncd.conf 配置文件

    [root@rsync-server-1 ~]# cat > /etc/rsyncd.conf << EOF #Rsync server #created by sunsky 00: ...

  9. 如何查看Codeforces的GYM中比赛的数据

    前置条件:黄名(rating >= 2100) 或者 紫名(rating >= 1900)并且打过30场计分的比赛. 开启:首先打开GYM的界面,如果符合要求会在右边展示出一个Coach ...

  10. uiautomatorviewer不能直接截取手机屏幕信息

    本身可以用sdk——>tools里自带的ui automator viewer截取如果截取不了,采用以下方法: 新建一个文本文档,名字自己起如uni.bat(注意把后缀给改成.bat) adb ...