0
0
Spring Bootframework~5 mins

@Value for property injection in Spring Boot

Choose your learning style9 modes available
Introduction

The @Value annotation helps you get values from configuration files into your code easily. It saves you from hardcoding values.

You want to use a database URL stored in application.properties inside your code.
You need to inject a timeout value that might change without changing the code.
You want to read a custom message or label from your config file to show in your app.
You want to keep secret keys or tokens outside your code and load them safely.
You want to configure feature flags that can be turned on or off via properties.
Syntax
Spring Boot
@Value("${property.key}")
private DataType variableName;

The ${property.key} is the key name in your properties file.

Make sure the property exists in your application.properties or application.yml.

Examples
This injects the value of app.name from your properties into appName.
Spring Boot
@Value("${app.name}")
private String appName;
This injects server.port or uses 8080 as a default if the property is missing.
Spring Boot
@Value("${server.port:8080}")
private int serverPort;
This injects a boolean flag from properties, defaulting to false if not set.
Spring Boot
@Value("${feature.enabled:false}")
private boolean featureEnabled;
Sample Program

This Spring Boot app reads app.greeting and app.version from properties. It prints them when the app starts. If app.version is missing, it uses "1.0" as default.

Spring Boot
package com.example.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;

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

@Component
class PropertyPrinter implements CommandLineRunner {

    @Value("${app.greeting}")
    private String greeting;

    @Value("${app.version:1.0}")
    private String version;

    @Override
    public void run(String... args) {
        System.out.println(greeting + " - Version: " + version);
    }
}
OutputSuccess
Important Notes

If the property is missing and no default is given, the app will fail to start.

You can use @Value on fields, constructor parameters, or setter methods.

For complex configurations, consider using @ConfigurationProperties instead.

Summary

@Value injects config values into your Spring beans.

You can provide default values using a colon : inside the expression.

It helps keep your code flexible and easy to configure.