How to Use @Value Annotation in Spring

@Value is a Spring annotation that allows you to inject a property value from a configuration file into a field in your application. This can be useful for injecting values such as database connection strings, API keys, or other application-specific configurations.

To use @Value in a Spring Boot application, follow these steps:

Step 1. Add the @Value annotation to the field

The first step is to add the @Value annotation to the field you wish to inject a value. For example:

@Value("${database.username}")
private String databaseUsername;

Step 2. Create Configuration Property

The next step is to create a configuration file in your application’s classpath. This file can be named application.properties or application.yml, and should contain the property key and value you wish to inject. For example:

database.username=myusername

Step 3. Read Configuration Value

You can now use @Value annotation to read the configuration property value. For example:

@Value("${database.username:defaultUsername}")
private String databaseUsername;

In this case, if the database.username property is not found in the configuration file, the field will be set to “defaultUsername“.

Injecting Multiple Values

If you need to inject multiple values into a single field, you can use the @Value annotation with a placeholder. For example:

@Value("${database.url}/${database.name}")
private String databaseUrl;

This will inject the values of the database.url and database.name properties into the databaseUrl field, separated by a forward slash.

Using the @Value annotation can help make your Spring Boot application more configurable and easier to maintain, as you can easily change property values without modifying the code itself. Just be sure to keep your configuration file safe and secure, as it may contain sensitive information such as API keys or database passwords.

To learn more, check out the Spring Boot tutorials page.

Happy learning!