Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot configuration: how to return always same random value when referenced?

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.

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

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

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

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

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

@Value("${APP_ID}")
private String 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.

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

like image 545
mister.elastic Avatar asked Mar 14 '18 09:03

mister.elastic


Video Answer


2 Answers

One way to do it (as suggested by wilkinsoa in this thread) is to "bind a single random value into a @ConfigurationProperties annotated bean and then use that bean to configure anything else that needed the same value."

This results in an application.properties file:

app.id=${random.uuid}

The configuration properties file is:

@Configuration
@ConfigurationProperties(prefix = "app")
public class AppProperties {

  private String id;

  public String getId() {
    return this.id;
  }

  public void setId(String id) {
    this.id = id;
  }
}

The class using the id:

@Component
public class DoStuff {

  private AppProperties appProperties;

  @Autowired
  public DoStuff(AppProperties appProperties) {
    this.appProperties = appProperties;
  }
}
like image 111
mister.elastic Avatar answered Sep 29 '22 23:09

mister.elastic


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();
}

and then reference it like:

integration.test.random.seed=#{T(com.yourdomain.config.TestConfig).RANDOM_LONG}
rabbitmq.queue=queueName_${integration.test.random.seed}
like image 29
Dmytro Verbivskyi Avatar answered Sep 29 '22 22:09

Dmytro Verbivskyi