Close

Spring Boot - Generating Random Properties

[Last Updated: Aug 26, 2017]

RandomValuePropertySource can generate random values for any properties that starts with "random.". This PropertySource is automatically applied on finding property values of format "${random.xyz..}.

Let's see an example to understand how to use it.

Example

The external properties

src/main/resources/application.properties

#random int
app.location-x=${random.int}
app.location-y=${random.int}

#random int with max
app.user-age=${random.int(100)}

#random int range
app.max-users=${random.int[1,10000]}

#random long with max
app.refresh-rate-milli=${random.long(1000000)}

#random long range
app.initial-delay-milli=${random.long[100,90000000000000000]}

#random 32 bytes
app.user-password=${random.value}

#random uuid. Uses java.util.UUID.randomUUID()
app.instance-id=${random.uuid}

@ConfigurationProperties class

@Component
@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;
    .............
}

Note that, we can also use @Value instead of @ConfigurationProperties to access random properties.

The Main class

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

Output

2017-08-26 11:22:46.923  INFO 236 --- [mpleMain.main()] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
MyAppProperties{
locationX=247678689,
locationY=632374795,
userAge=95,
maxUsers=4709,
refreshRateMilli=655957,
initialDelayMilli=48846676108633928,
userPassword='13f5929528de7f224c96fd51dde283f1',
instanceId=ad46ce0a-0d50-47f2-b519-bc0b8b0e930b
}
2017-08-26 11:22:47.047 INFO 236 --- [ Thread-2] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown

Example Project

Dependencies and Technologies Used:

  • Spring Boot 1.5.6.RELEASE
    Corresponding Spring Version 4.3.10.RELEASE
  • spring-boot-starter : Core starter, including auto-configuration support, logging and YAML.
  • JDK 1.8
  • Maven 3.3.9

RandomValuePropertySource Example Select All Download
  • random-value-property-source
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources
          • application.properties

    See Also