零、学习目标
一、项目进行多环境配置的必要性
–在实际开发中,应用程序通常需要部署到不同的运行环境中,例如开发环境、测试环境、生产环境等。不同的环境可能需要不同的环境配置,针对这种情况,不可能手动变更配置文件来适应不同的开发环境,通常需要对项目进行多环境配置,Spring Boot框架提供了两种多环境配置的方式,分别是Profile文件多环境配置和@Profile注解多环境配置。同时,会额外讲解在Spring Boot配置文件中设置属性时,除了可以像前面示例中显示的配置属性值外,还可以使用随机值和参数间引用对属性值进行设置。
二、使用Profile文件进行多环境配置
1.创建Spring Boot Web项目ProfileDemo01
2.创建多环境配置文件
(1)首先把application.properties改为application.properties.disable让这个文件无效
(2)创建application.yaml
#指定环境 choose environment
spring:
profiles:
active: dev #dev environment
(3) 创建 application-xxx.yaml
–1.创建application-dev.yaml
# 配置服务器 setting service
# 模拟环境 Dev -environment
server:
port: 8081
servlet:
context-path: /dev
–2.创建application-test.yaml
# 配置服务器 setting service
# 测试环境 test environment
server:
port: 8083
servlet:
context-path: /test
–3.创建application-pro.yaml
# 配置服务器 setting service
# 生产环境 pro environment
server:
port: 8082
servlet:
context-path: /pro
3.创建控制器
(1) –在net.dw.boot里创建controller子包,在子包里创建ProfileController
+
package net.dw.boot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProfileController {
@GetMapping("hello")
public String hello(){
return "<h1 style='color:red;text-align: center;'>Hello World!</h>";
}
}
(2) 启动测试
–在浏览器里面输入http://localhost:8081/dev/hello
4.使用maven
(1).使用IDEA将Maven项目打成jar包
–Maven - ProfileDemo01 - LifeCycle - package,单击右键,在快捷菜单里执行“Run Maven Build”
–在target目录里查看生成的项目jar包profiledemo01-0.0.1-SNAPSHOT.jar
java -jar ProfileDemo01-0.0.1-SNAPSHOT.jar --spring.profiles.active=pro
–访问http://localhost:8082/pro/hello
–虽然打包的时候是dev,终端启动带了参数,遵循就近原则,终端的参数会覆盖包内的默认参数
–Ctrl + C 停止运行
–试试dev
java -jar ProfileDemo01-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
http://localhost:8081/dev/hello
四随机值设置以及参数间引用
(1)创建Spring Boot Web项目RandomSetDemo
(2)在全局配置文件里配置随机值![请添加图片描述](https://img-blog.csdnimg.cn/66ca1f25aa0d42ef82e3a50ab45ed898.png)
#任意一个随机数
my.number=${random.value}
#一个随机整数
my.integer=${random.int}
#一个长整型的随机数
my.long=${random.long}
#获取一个随机的UUID值
my.uuid=${random.uuid}
#小于10的随机整数
my.number.less=${random.int(10)}
#随机产生1024至65535之间的数
my.number.range=${random.int[1024,65535]}
(3)在测试类里测试配置的随机数
package net.dw.boot;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class RandomSetDemoApplicationTests {
//注入配置文件里的属性
@Value("${my.number}")
private String number;
@Test
void contextLoads() {
//输出配置文件里的属性
System.out.println(number);
}
}
–运行结果
–产生的是32位的十六进制数对应的字符串