Using the @Value annotation in Spring Boot

problem

You want to use a value from a properties file to load into a field in your class. In this post we will see how to do that using Spring boot.

SOLUTION

Using the @Value annotation. We can place this annotation on a field, e.g. String. Let’s say we wish to load a default message from our application.properties to one of our fields.

application.properties
				
					message="A default message"

				
			

Simply we use that annotation, e.g on a field to load the value into it:

ValueApplication.java
				
					@Value("${message}")
private String message;

				
			
running

Let’s create a complete Rest Controller and retrieve the value from the frontend.

ValueApplication.java
				
					package com.programmerabroad.value;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class ValueApplication {

    @Value("${message}")
    private String message;

    public static void main(String[] args) {
        SpringApplication.run(ValueApplication.class, args);
    }

    @GetMapping("/")
    public String index() {
        return message;
    }

}


				
			

We open our browser on the default url that Spring boot runs: http://localhost:8080/ 

output
Spring boot @value example

conclusion

In this post we saw how to use the @Value annotation on a field and load a String message from the application.properties file into a class field and subsequently print it to the Http response body.

Reference: 

https://docs.spring.io/spring-framework/reference/core/beans/annotation-config/value-annotations.html 

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪