Explain @Value annotation with example

Explain @Value annotation with example

The `@Value` annotation in Spring is used to inject values into fields from property files, system properties, or expressions. It provides a convenient way to externalize configuration values and make them available within your Spring beans.

  • Property File Injection: Allows injecting values from property files (e.g., `application.properties` or `application.yml`).
  • System Property Injection: Enables injection of system properties.
  • Expression Injection: Supports SpEL (Spring Expression Language) to evaluate expressions.

Value annotation

Example

Step 1: Create a Spring Boot Application

Ensure you have the necessary dependencies in your `pom.xml` (for Maven) or `build.gradle` (for Gradle).

Example
Maven Dependency:
```xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
```

Gradle Dependency:
```groovy
implementation 'org.springframework.boot:spring-boot-starter'
```

Step 2: Create the Main Application Class

Create the main class for the Spring Boot application.

Example
```java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

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

Explanation:

  • @SpringBootApplication: Indicates a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning.

Step 3: Define a Properties File

Create a properties file (application.properties) in the src/main/resources directory.

Example

```properties
app.name=MySpringBootApp
app.version=1.0.0
app.description=This is a sample Spring Boot application
```

Explanation:

  • application.properties: A file used to externalize configuration settings, which can be injected into Spring beans.

Step 4: Use @Value Annotation in a Bean

Create a component class and use the @Value annotation to inject property values.

Example

```java
package com.example.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class AppConfig {

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

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

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

    public String getAppName() {
        return appName;
    }

    public String getAppVersion() {
        return appVersion;
    }

    public String getAppDescription() {
        return appDescription;
    }
}
```

Explanation:

  • @Component: Indicates that this class is a Spring component, which means it is a candidate for component scanning and will be managed by Spring.
  • @Value("${app.name}"): Injects the value of app.name from the application.properties file into the appName field.

Step 5: Create a Controller to Use AppConfig

Create a REST controller to expose the injected values.

Example
```java
package com.example.demo.controller;

import com.example.demo.AppConfig;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/config")
public class ConfigController {

    private final AppConfig appConfig;

    public ConfigController(AppConfig appConfig) {
        this.appConfig = appConfig;
    }

    @GetMapping
    public String getConfig() {
        return String.format("App Name: %s, Version: %s, Description: %s",
                appConfig.getAppName(), appConfig.getAppVersion(), appConfig.getAppDescription());
    }
}
```

Explanation:

  • @RestController: Indicates that this class is a REST controller and its methods return data directly to the HTTP response body.
  • @RequestMapping("/config"): Maps the URL /config to the ConfigController methods.
  • @GetMapping: Maps HTTP GET requests to the getConfig method, which returns the configuration values.

Step 6: Running the Application

Run the application from the main class (DemoApplication). You can test the endpoint using a tool like Postman or by navigating to the URL in your browser:

Example
GET request to http://localhost:8080/config should return the application configuration values like:

  App Name: MySpringBootApp, Version: 1.0.0, Description: This is a sample Spring Boot application

Conclusion Value annotation with example

  • @Value: Used to inject values from property files, system properties, or expressions into Spring beans. It helps in externalizing configuration and provides flexibility in managing application settings.
  • Example: Demonstrated how to use @Value to inject values from a properties file into a Spring bean and then access these values through a REST controller.

Homepage

Readmore