随机属性配置:Spring Boot中的动态属性注入

随机属性配置:Spring Boot中的动态属性注入

在Spring Boot应用开发过程中,我们经常需要为某些属性注入动态值,例如随机数、UUID等。Spring Boot提供了一个非常方便的特性,允许我们通过RandomValuePropertySource来实现这一需求。本文将通过一个具体的示例,展示如何使用这一特性。

外部属性配置

首先,我们需要在application.properties文件中定义一些以"random."开头的属性,Spring Boot会自动为这些属性生成随机值。

# 随机整数
app.location-x=${random.int}
app.location-y=${random.int}

# 随机整数,指定最大值
app.user-age=${random.int(100)}

# 随机整数范围
app.max-users=${random.int[1,10000]}

# 随机长整型,指定最大值
app.refresh-rate-milli=${random.long(1000000)}

# 随机长整型范围
app.initial-delay-milli=${random.long[100,90000000000000000]}

# 随机生成32字节
app.user-password=${random.value}

# 随机UUID
app.instance-id=${random.uuid}

配置属性类

接下来,我们定义一个@ConfigurationProperties类来绑定这些属性。

@ConfigurationProperties("app")
public class MyAppProperties {
    private int locationX;
    private int locationY;
    private int userAge;
    private int maxUsers;
    private long refreshRateMilli;
    private long initialDelayMilli;
    private String userPassword;
    private UUID instanceId;

    // Getters and Setters
}

主类配置

在Spring Boot的主类中,我们通过ConfigurableApplicationContext获取MyAppProperties的Bean,并打印出来。

@SpringBootApplication
public class ExampleMain {
    public static void main(String[] args) throws InterruptedException {
        SpringApplication springApplication = new SpringApplication(ExampleMain.class);
        springApplication.setBannerMode(Banner.Mode.OFF);
        springApplication.setLogStartupInfo(false);
        ConfigurableApplicationContext context = springApplication.run(args);
        MyAppProperties bean = context.getBean(MyAppProperties.class);
        System.out.println(bean);
    }
}

输出示例

运行上述代码后,控制台将输出如下信息,展示了注入的随机属性值。

MyAppProperties{
    locationX=247678689,
    locationY=632374795,
    userAge=95,
    maxUsers=4709,
    refreshRateMilli=655957,
    initialDelayMilli=48846676108633928,
    userPassword='13f5929528de7f224c96fd51dde283f1',
    instanceId=ad46ce0a-0d50-47f2-b519-bc0b8b0e930b
}

示例项目技术栈

  • Spring Boot 1.5.6.RELEASE
  • Spring Framework 4.3.10.RELEASE
  • spring-boot-starter: 核心启动器,包括自动配置支持、日志和YAML。
  • JDK 1.8
  • Maven 3.3.9

通过这个示例,我们可以看到Spring Boot如何方便地为应用注入动态属性。这在开发需要随机数据的场景中非常有用,例如测试、模拟数据生成等。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

t0_54coder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值