SpringBoot使用注意事项
@Value为属性赋值
msg:
hello:"hello"
msg.hello=hello word
Controller
@RestController
@RequestMapping("hello")
public class HelloController {
@Value("${msg.hello}")
private String msg;
@GetMapping("doGetMsg")
public String doGetMsg(){
return msg;
}
}
1.2properties文件为属性赋值
业务有时会需要动态赋值,如果将大量的业务数据写到yml文件中,导致代码混乱,最好指定properties文件为业务赋值
1.2.1编辑properties文件
#语法:
#数据结构: key=value
#注意事项: 不要添加""号 本身就是字符串.
#字符集编码: 写法采用utf-8,程序读取时采用ISO-8859-1
pro.msg=配置信息
1.2.2动态赋值
controller层
@RestController
@RequestMapping("hello")
@PropertySource(value= "classpath:/properties/msg.properties",encoding = "UTF-8")
public class HelloController {
@Value("${msg.hello}")
private String msg;
@GetMapping("doGetMsg")
public String doGetMsg(){
System.out.println(msg);
return msg;
}
}
2.1环境切换
要求: 不管是几个环境,要求配置项都必须相同,值可以不同
语法:
1.使用—实现YML配置文件的分割
2.定义环境名称
3.定义默认环境名称
#指定默认的环境
spring:
profiles:
active: test
---
#关于YML配置文件说明
# 1.数据结构 key=value
# 2.数据类型 默认都是字符串 如果需要类型转化,则框架已经在内部完成
# 3.yml写法: 1.key: (空格)value 2.有层级结构 编辑时注意
# 4.字符集编码: 默认程序加载时都是UTF-8
#定义环境名称
spring:
config:
activate:
on-profile: dev
server:
port: 8080
#项目发布的路径
servlet:
# /缺省值 localhost:8080/jt/xxxx请求路径
context-path: /
#2.为属性赋值 hello代表前缀 key=hello.msg
hello:
msg: "我喜欢开发"
#环境分割线
---
spring:
config:
activate:
on-profile: test
server:
port: 8090
#项目发布的路径
servlet:
# /缺省值 localhost:8080/jt/xxxx请求路径
context-path: /
#2.为属性赋值 hello代表前缀 key=hello.msg
hello:
msg: "我喜欢测试"