Spring Boot配置:引用时如何返回始终相同的随机值? [英] Spring boot configuration: how to return always same random value when referenced?

查看:74
本文介绍了Spring Boot配置:引用时如何返回始终相同的随机值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有应用程序属性 APP_ID ,应该随机生成(UUID),并且对于整个Spring Boot应用程序应该具有相同的值。

I have the application property APP_ID that should be randomly generated (UUID) and that should have the same value for the entire Spring Boot application.

我做了以下工作:我在 application.properties 文件中定义了 APP_ID = $ {random。 uuid}

What I did was the following: I defined in the application.properties file the APP_ID=${random.uuid}.

已成功创建UUID,但是对于每个属性引用 @Value( $ {APP_ID} )我将获得一个不同的UUID。

The UUID gets created successfully, however for every property reference @Value("${APP_ID}") I will get a different UUID.

示例:在类 Foo 中想要使用 appId

Example: In class Foo I want to use the appId:

@Value("${APP_ID}")
private String appId;

在类 Bar 中,我想使用 appId 也是:​​

In class Bar I want to use the appId, too:

@Value("${APP_ID}")
private String appId;

但是,<$ c中的 appId $ c> Bar 始终与 Foo 中的 appId 不同。

However, the appId in Bar is always different to the appId in Foo.

我已经阅读了线程这种行为是正确的。

I have read in this thread that this behavior is the correct one.

什么是总是获得相同的 APP_ID 的正确实现方式?

What would be proper implementation to always get the same APP_ID?

推荐答案

您可以生成随机值作为测试的常数。

You can generate random value as constant for your test.

package com.yourdomain.config;

import org.apache.commons.lang3.RandomUtils;

public class TestConfig {

    public static final long RANDOM_LONG = RandomUtils.nextLong();
}

,然后像这样引用它:

integration.test.random.seed=#{T(com.yourdomain.config.TestConfig).RANDOM_LONG}
rabbitmq.queue=queueName_${integration.test.random.seed}

这篇关于Spring Boot配置:引用时如何返回始终相同的随机值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆