从头撸springboot(二)

从头撸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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值