从头撸springboot(二)——配置文件详解:自定义属性、随机数、多环境配置等
刚开始工作,感觉springboot基础不牢靠,决定从头撸一遍springboot
- 全教程:https://www.zhihu.com/question/53729800
- 今日工作:https://blog.didispace.com/spring-boot-learning-1/
1.自定义属性
1)修改application.properties
com.example.blog.name=123
com.example.blog.title=Spring Boot456
com.example.blog.content=${com.example.blog.name}and${com.example.blog.title}
注:
(1) 汉字会乱码
(2) 不用加引号,直接写
(3) 可以使用${}方式直接引用参数
2)新建BlogProperties类
@Component
@Data
public class BlogProperties {
@Value("${com.example.blog.name}")
private String name;
@Value("${com.example.blog.title}")
private String title;
@Value("${com.example.blog.content}")
private String content;
}
3)修改test
@Test
public void getHello2() throws Exception {
Assert.assertEquals(blogProperties.getName(), "123");
Assert.assertEquals(blogProperties.getTitle(), "Spring Boot456");
Assert.assertEquals(blogProperties.getContent(), "123andSpring Boot456");
}
4)直接run ‘getHello2()’
test成功!
2.随机数
修改application.properties
# 随机字符串
com.example.blog.value=${random.value}
# 随机int
com.example.blog.number=${random.int}
# 随机long
com.example.blog.bignumber=${random.long}
# 10以内的随机数
com.example.blog.test1=${random.int(10)}
# 10-20的随机数
com.example.blog.test2=${random.int[10,20]}
注:
(1) int long类型不要写错
3.通过命令行设置属性值
java -jar xxx.jar --server.port=8888 //在命令行中指定端口为8888
SpringApplication.setAddCommandLineProperties(false); //取消指定
4.多环境配置
使用application-{profile}.properties的格式配置不同环境,例如:
application-dev.properties:开发环境
application-test.properties:测试环境
application-prod.properties:生产环境
总结:
(1) application.properties中配置通用内容
(2) 设置spring.profiles.active=dev,以开发环境为默认配置
(3) application-{profile}.properties中配置各个环境不同的内容
(4) 通过命令行方式去激活不同环境的配置
至此,第二部分结束orz