Spring Boot 学习笔记 2 : Random

本文介绍了 Spring Boot 中的 RandomValuePropertySource 类,用于生成随机值,如 integers、longs、uuids 和 strings。详细讲解了配置文件的设置、Controller 示例以及测试方法,并提醒了注意事项,包括不能使用 static 修饰符和避免键名以 'random' 开头,以防异常。同时,深入解析了 RandomValuePropertySource 的内部工作原理,涉及 getProperty、getRandomValue、getRange 和 getNextIntInRange 等方法的调用流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官方文档介绍

The RandomValuePropertySource is useful for injecting random values (e.g. into secrets or test cases). It can produce integers, longs, uuids or strings, e.g.

RandomValuePropertySource 类通常用来注入 int,long,uuid 和 string 类型的随机值。

The random.int* syntax is OPEN value (,max) CLOSE where the OPEN,CLOSE are any character and value,max are integers. If max is provided then value is the minimum value and max is the maximum (exclusive).

random.int* 的语法是 OPEN value (,max) CLOSE 。OPEN 和 CLOSE 可以是 任意字符,用来分隔方法参数。value, max 是 int 类型的整数。如果 max 参数存在,则 value 表示取值范围的最小值,max 表示最大值(不包含 max)。


编写配置文件

application.properties 文件配置:

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

application.yml 文件配置:

my:
    value: ${
  
  random.value}
    int: ${
  
  random.int}
    long: ${
  
  random.long}
    uuid: ${
  
  random.uuid}
    int.less.than.ten: ${
  
  random.int(10)}
    # 100前面和1000后面可以是 -,(,[ 等任意字符
    int.in.range: ${
  
  random.int-100,1000-}

编写 Controller 类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值