How to read integer value from properties file in spring boot

What you will learn here about Spring Boot

  • How to read integer value from properties file in spring boot

How to read integer value from properties file in spring boot

Please follow the following steps to know how to read integer value from properties file in spring boot
1)First create a simple maven project

2)Then add spring starter web dependency in your pom.xml file which is given below

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

3)Now Add minimum and maximum number in properties file which is given below

random-number-service.minimum=0
random-number-service.maximum=1000

4)Now create class which will read minimum and maximum number from properties file which is given below

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties("random-number-service")
public class RandomNumberConfiguration {
    private int minimum;
    private int maximum;

    public int getMinimum() {
        return minimum;
    }
    public void setMinimum(int minimum) {
        this.minimum = minimum;
    }
    public int getMaximum() {
        return maximum;
    }
    public void setMaximum(int maximum) {
        this.maximum = maximum;
    }
}

5)Now create a restcontroller which will use minimum and maximum number to create a random number between minimum and maximum number.

package com.bytesofgigabytes.ReadIntegerProperty;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RandomNumberController {
    @Autowired
    RandomNumberConfiguration randomNumberConfiguration;

    @GetMapping("/random")
    public int getRandomNumber(){
        return (int) (Math.random() *
                (randomNumberConfiguration.getMaximum() - randomNumberConfiguration.getMinimum())) +
                randomNumberConfiguration.getMinimum();
    }
}

how to read integer value from properties file in spring boot

6)Now please run your spring boot application

7)Now go to browser and hit localhost:8080/random which is shown below.
spring boot read integer value from properties file in

You may also like...