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);
}
}OutputMyAppProperties{ locationX=-1605004570, locationY=-2030067222, userAge=52, maxUsers=4291, refreshRateMilli=452923, initialDelayMilli=84107776829390247, userPassword='4a4ab7bd60cd4fb841cb97cebf4d0459', instanceId=7d9088b8-2668-4383-aa08-4b33ce27b58b }
Example ProjectDependencies 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
|