SpringBoot 配置文件默认为application.properties,但是本章节主要讲解yaml文件配置,因为现在的趋势是使用yaml,它是类似于标准通用标记语言的子集XML的数据描述语言,语法比XML简单很多。

pom文件贴在最后面:

一、自定义属性与加载
我们把之前项目中的配置文件application.properties改成application.yml

test:
user:
username : zhangsan
age :
toString: the age of ${test.user.username} is ${test.user.age}

属性类

package cn.saytime.bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; @Component
public class PropertiesConfig { @Value("${test.user.username}")
private String username; @Value("${test.user.age}")
private String age; @Value("${test.user.toString}")
private String toString; // ... Getter Setter }

测试Controller

package cn.saytime.web;

import cn.saytime.bean.PropertiesConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; @RestController
public class TestController { @Autowired
private PropertiesConfig propertiesConfig; @RequestMapping(value = "test", method = RequestMethod.GET)
public String test(){
// return propertiesConfig.getUsername() + ":" + propertiesConfig.getAge();
return propertiesConfig.getToString();
}
}

访问 http://127.0.0.1/test

或者测试单元: 注意:要在springboot启动类下面新建测试类

package cn.demo;

import java.util.Properties;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import cn.demo.bean.Config;
import cn.demo.bean.Person;
import cn.demo.bean.User; @RunWith(SpringRunner.class)
@SpringBootTest
public class PropertiesTest { @Autowired
private User user; @Autowired
private Person person; //新建的test.yml和 person.yml文件,取不到值,都是null,但是新建的person.properies可以取值。 @Test
public void test() {
System.out.println("server display name:" + user.getUsername());
System.out.println("server address:" + user.getAge());
System.out.println("server emain:" + user.getEmail());
} @Test
public void test2() {
System.out.println("person-infomation:" + person.toString());
} }

二、自定义属性注入bean
将上面application.yml文件中的test.user注入到User对象里,注意这里的prefix指定的是test.user,对应配置文件中的结构

@Component
@ConfigurationProperties(prefix = "test.user")
public class User { private String username; private int age; public String getUsername() {
return username;
} // Getter Setter
}
@RestController
public class TestController { @Autowired
private User user; @RequestMapping(value = "test2", method = RequestMethod.GET)
public String test2(){
return user.getUsername() + ":" + user.getAge();
}
}

访问 http://localhost:8080/test2 ==> zhangsan : 18

三、自定义额外的配置文件
比如我们不想把有些配置配置在application.yml/properties中。新建其他配置文件。这里比如新建test.yml文件。配置内容如上面的application.yml一样。那么我们注入对象时,应该这么写

@Configuration
@PropertySource(value = "classpath:test.yml")
@ConfigurationProperties(prefix = "test.user")
四、多个环境配置文件
在现实的开发环境中,我们需要不同的配置环境;格式为application-{profile}.properties,其中{profile}对应你的环境标识,比如:

application-test.properties:测试环境
application-dev.properties:开发环境
application-prod.properties:生产环境
怎么使用?只需要我们在application.yml中加:

spring:
profiles:
active: dev

因为主入口都是application.yml,这里指定配置文件为dev,即启用application-dev.yml文件

其中application-dev.yml:

server:
port: 8888

启动工程,发现程序的端口不再是8080,而是8888,表示开发环境配置成功。

六、官方支持默认配置文件属性
http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#common-application-properties

七、属性加载优先级
1. @TestPropertySource 注解
2. 命令行参数
3. Java系统属性(System.getProperties())
4. 操作系统环境变量
5. 只有在random.*里包含的属性会产生一个RandomValuePropertySource
6. 在打包的jar外的应用程序配置文件(application-{profile}.properties,包含YAML和profile变量)
7. 在打包的jar内的应用程序配置文件(application-{profile}.properties,包含YAML和profile变量)
8. 在@Configuration类上的@PropertySource注解
9. 默认属性(使用SpringApplication.setDefaultProperties指定)
也就是说比如我配置文件配置了一个name=zhangsan,然后将项目打成jar,运行的时候,如果我们使用 java -jar app.jar --name="Spring",那么注入的进去的就是Spring,优先级高

八、配置文件优先级
查看SpringBoot官方文档,可以发现

翻译:

当前目录下的一个/config子目录
当前目录
一个classpath下的/config包
classpath根路径(root)
也就是说:如果我们有多个配置文件,比如 src/main/resource/application.yml

test:
user:
username : zhangsan
age : 18
toString: the age of ${test.user.username} is ${test.user.age} name: SpringBoot-root test2: ${test1}-root test3: SpringCloud-root server:
port: 8080
src/main/resource/config/application.yml test:
user:
username: lisi-config name: SpringBoot-config test1: ${name}-config test4: ${test3}-config server:
port: 9090

根据优先级,可以得到能够加载到SpringBoot应用的属性为:

test:
user:
username : lisi
age : 18
toString: the age of lisi is 18 name: SpringBoot-config
test1: SpringBoot-config-config
test2: SpringBoot-config-config-root
test3: SpringCloud-root
test4: SpringCloud-root-config server:
port: 9090

如果你能够得到上面的结果,表示你已经懂了。

注意优先级高的配置文件中存在和优先级低的配置文件相同属性时,取优先级高配置文件的,不冲突的时候,优先级低的配置文件属性同样会被加载,而不是只加载优先级高的配置文件属性。

九、简单总结
1、普通自定义属性,使用@Value("${xxx}")注入 2、注入对象,使用@ConfigurationProperties(prefix="test.user")

pom:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.demo</groupId>
<artifactId>springboot_peizhi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot_peizhi</name>
<url>http://maven.apache.org</url> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.2</version>
</dependency>
<!-- Spring-Mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>

SpringBoot(三) 配置文件 篇章的更多相关文章

  1. SpringBoot 读取配置文件及profiles切换配置文件

    读取核心配置文件 核心配置文件是指在resources根目录下的application.properties或application.yml配置文件,读取这两个配置文件的方法有两种,都比较简单. 先创 ...

  2. springboot指定配置文件运行

    1.springboot指定配置文件运行 创建三个配置文件如下: application.properties内容如下: spring.profiles.active=rabbit如上配置,在运行时就 ...

  3. SpringBoot获取配置文件,就这么简单。

    在讲SpringBoot 获取配置文件之前我们需要对SpringBoot 的项目有一个整体的了解,如何创建SpringBoot 项目,项目结构等等知识点,我在这里就不一一讲述了,没有学过的小伙伴可以自 ...

  4. SpringBoot 属性配置文件数据注入配置和yml与properties区别

    前言 我们知道SpringBoot 通过配置类来解放一堆的xml文件配置,通属性配置文件,来进行,系统全局属性配置,这样极大的简化了我们开发过程,java web 也可以甜甜的从此 快速配置 Spri ...

  5. SpringBoot之配置文件加载位置

    1.SpringBoot启动会扫描application.properties或者application.yml文件作为springboot的配置文件.默认创建项目生成application.prop ...

  6. [SpringBoot] - 了解什么是SpringBoot,使用SpringBoot的配置文件

    首先明白Spring是什么,Spring是Java开发的一个框架,为了方便简化Java开发. 什么是注解(注解式开发)? Spring的常用注解有哪些? 假如用SpringBoot构建一个网站程序,应 ...

  7. springboot读取配置文件的顺序

    前言 今天测试一些东西,发现配置文件连接的数据库一直不正常,数据也不对,今天请教了之后,原来springboot的配置文件加载不仅仅是项目内的配置文件. 正文 项目目录是这样的:文件夹下有:项目,ap ...

  8. SpringBoot读取配置文件源码探究

    1. SpringBoot读取配置文件源码探究 1.1. 概览 springboot的源码是再原来的Spring源码上又包了一层,看过spring源码都知道,当我们从入口debug进去的时候,原来的S ...

  9. springboot yml配置文件注入值

    1.编写javabean: package com.example.springboot.bean; import org.springframework.boot.context.propertie ...

  10. SpringBoot:配置文件及自动配置原理

    西部开源-秦疆老师:基于SpringBoot 2.1.6 的博客教程 秦老师交流Q群号: 664386224 未授权禁止转载!编辑不易 , 转发请注明出处!防君子不防小人,共勉! SpringBoot ...

随机推荐

  1. Implement Custom Business Classes and Reference Properties实现自定义业务类和引用属性(EF)

    In this lesson, you will learn how to implement business classes from scratch. For this purpose, the ...

  2. SAP会计年度变式

       会计年度变式用来确定SAP系统中每个公司的会计记账期间的变式.顾名思议,每个公司的会计年度变式必须与其实际使用的会计年度匹配.     在SAP系统中,每个会计年度最多允许有16个记账期间,其中 ...

  3. XSS原理及其相应工具使用

    XSS(厉害程度:只要js能实现什么功能,xss就能对client造成什么伤害):   原理:通过web站点漏洞,向客户端交付恶意脚本代码,实现对客户端的攻击目的 主要攻击目的(网页挂马:通过XSS向 ...

  4. 剑指offer 22:验证栈的压入、弹出序列

    题目描述 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序.假设压入栈的所有数字均不相等.例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压 ...

  5. MongoDB的模糊查询操作(类关系型数据库的 like 和 not like)

    1.作用与语法描述 作用: 正则表达式是使用指定字符串来描述.匹配一系列符合某个句法规则的字符串.许多程序设计语言都支持利用正则表达式进行字符串操作.MongoDB 使用 $regex 操作符来设置匹 ...

  6. ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/itsdangerous' Consider using the `--user` option or check the permissions

    近期练习flask写个blog, 安装flask扩展时 pip install Flask-WTF 报ERROR: Could not install packages due to an Envir ...

  7. APK更新集成实践

    任务目标:将内网APK打包后最新下载链接.更新时间.更改日志显示在一个我自己制作的APP里 任务作用:我们在内网测试时更新下载APK更加便捷,并且能够清楚目标APK的版本情况,回归.验证做到有的放矢 ...

  8. 《移动WEB前端高级开发实践@www.java1234.com.pdf》

    HTTP服务器: http-server 3.6.4 利用 Performance API 分析网站性能 页面加载生命周期 4. CSS3 伪类.伪元素, 看https://www.runoob.co ...

  9. Ant默认配置文件不是build.xml该如何编写命令进行编译打包

    Ant的构件文件是基于XML编写的,默认名称为build.xml. ant命令默认寻找build.xml文件.若文件名为hello.xml时,读者还需要对命令做少许改变, 改为:ant –f hell ...

  10. 66000][12505] Listener refused the connection with the following error: ORA-12505, TNS:listener does not currently know of SID given in connect descriptor oracle.n et.ns.NetException: Listener refuse

    新装的idea开发工具后连接数据库出现如题所示错误. 1.网上搜了不少的文章,没有解决我的问题.后来细心看了一下url: 一开始url是这样子的. jdbc:oracle:thin:@:s21_pdb ...