Spring Boot : Configuring Random values

Kumar Pallav's photo
Kumar Pallav
·Oct 19, 2018·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Many times we need to get random values ,for example you need to generate random pin for verification or a some random value for email verification. Spring provides easy way to do it.

RandomValuePropertySource is used to inject random values. RandomValuePropertySource can produce integers, longs, uuids or strings.

In application.properties we will add following :


The above values are self explanatory . They are creating random values. In order to see if they work as expected let’s create a RequestMapping so that we access these value and display on UI /POSTMAN.

We will inject above defined properties via @Value annotation. Doing so we can also see that spring will keep the type safety in consideration. If we take a Integer value to inject an integer it will inject integer , Long for long and so on . Let’s create another controller CommonController as below with a RequestMapping.

public class CommonController {
    private String random;
    private Integer randomInteger;
    private Long randomLong;
    private String randomUUID;
    private Integer randomLessThanHundred;
    private Integer randomWithinRange;

    protected MapgetRandomValues(){
     Map randomValues= new LinkedHashMap();
     return randomValues;

Here we can observe that we are using a Map to collect all values in our method and send them back. Once we hit http://localhost:8082/v1/random-values (Considering you are still giving port as command line parameter i.e.–server.port=8082) we will get following response.

“random”: “2b26227a3a78bbbac96617f094b613e6”,
“randomInteger”: 728349517,
“randomLong”: -529828434181910766,
“randomUUID”: “c5b8aa23-5992-48c3-9aed-f7b9e0e223c7”,
“randomLessThanHundred”: 5,
“randomWithinRange”: 7208

With above value , we can be assured that our RandomValuePropertySource is correctly working.

Share this