【SpringBoot笔记4】外置配置

SpringBoot允许你外置化项目的配置信息,你可以使用properties文件、YAML文件、环境变量、命令行参数来设置配置信息。

1 优先级

SpringBoot提供多种外部配置方式,这些方式的优先级如下(由高到低):

  1. 命令行参数
  2. 来自 java:comp/envJNDI 属性
  3. Java系统属性( System.getProperties()
  4. 操作系统环境变量
  5. RandomValuePropertySource 配置的 random.* 属性值
  6. jar 包外部的 application-{profile}.propertiesapplication.yml (带 spring.profile )配置文件
  7. jar包内部的 application-{profile}.propertiesapplication.yml (带 spring.profile )配置文件
  8. jar 包外部的 application.propertiesapplication.yml (不带 spring.profile )配置文件
  9. jar 包内部的 application.propertiesapplication.yml (不带 spring.profile )配置文件
  10. @Configuration 注解类上的 @PropertySource
  11. 通过 SpringApplication.setDefaultProperties 指定的默认属性

2 使用

2.1 自定义配置

例如,在项目中定义一个类MyBean,它的一个成员变量name的值需要从外部配置文件中读取,可以使用@Value注释:

@Component("myBean")
public class MyBean {
   

    @Value("${MyBean.name}")
    private String name;
}

${MyBean.name}表示获取变量MyBean.name的值,该变量可以在application.properties文件中定义:

MyBean.name=MyBean-HaHa

2.2 使用SpringBoot提供的随机值

SpringBoot内置了一个RandomValuePropertySource类,提供了生成随机值的功能。我们可以在配置文件中或者代码中直接通过random.*获取SpringBoot提供的随机值。

  • random.value—— 返回一个随机字符串
  • random.int —— 返回一个随机int类型值
  • random.long —— 返回一个随机long类型值
  • random.uuid —— 返回一个随机的uuid
  • random.int(10) —— 返回一个小于10int类型值
  • random.int[1024, 65536] —— 返回一个范围类的int类型值

可以在application.properties配置文件中获取并赋值给自定义的变量:

my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}

也可以直接在程序中取值:

@Component("myRandom")
public class MyRandom {
   

    @Value("${random.value}")
    //@Value("${my.secret}")
    private String secret
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值