【SpringBoot】12.全局配置文件(properties)与yml配置文件

一、SpringBoot全局配置文件

1.修改内嵌容器端口号

#application.properties
server.port=8888

2.自定义属性的配置

使用@Value来给成员变量赋值

#application.properties
msg=Hello world
@RestController
public class HelloWorldController {
	@Value("${msg}")
	private String msg;
    
	@RequestMapping("/hello")
	public String showMsg() {
		return this.msg;
	}
}

打印出“Hello world”

3.配置变量引用

#application.properties
hello=dxh
msg=Hello world ${hello}
@RestController
public class HelloWorldController {
	@Value("${msg}")
	private String msg;
    
	@RequestMapping("/hello")
	public String showMsg() {
		return this.msg;
	}
}

此时 最终打印结果为 “Hello world dxh”

4.随机值配置

语法:

#生成一个随机数
${random.int}
#限定范围
${random.int[1024,9999]} 
4.1配置随机值
#application.properties
hello=dxh
num=${random.int}
msg=Hello world ${hello} ${random.int}

返回“Hello world dxh 2092427377” ;
加粗数字为随机数,因为properties文件在容器启动时只会被载入一次,因此这时再刷新将不会更改。

用处:配置随机值,再程序中如果有一些运算需要一个随机值,那么可以使用该方式来生成,且只生成一次。

4.2配置随机端口
#application.properties
server.port=${random.int[1024,9999]}

用处:在springcloud的微服务中,我们是不需要记录ip与端口号的。那么我们也就不需要去维护服务的端口号。让他随机就可以了。

二、yml配置文件

是SpringBoot中新增的一种配置文件格式。

特点:具备天然的树状结构

1.yml配置文件与properties文件的区别

①配置文件的扩展名有变化

②配置文件中的语法有变化

2.yml配置文件的语法

  1. 在properties文件中是以"."分割,在yml中使用":"分割
  2. yml的数据格式和json格式很像,都是K-V结构的。并且是用过“: ”赋值
  3. 在yml中缩进一定不能使用TAB键,否则会报错
  4. 每个 K 的冒号后面一定要加一个空格
server:
      port: 8888

hello:
      msg: Helloworld
      msg2: Dxh
原文地址:https://www.cnblogs.com/isdxh/p/13529194.html