top of page
Search

A Comprehensive Guide to Using Spring’s @Value Annotation


Spring’s @Value annotation is a powerful tool for injecting values into your Spring-managed beans. Whether you’re pulling in values from properties files, system properties, or even evaluating complex expressions with the Spring Expression Language (SpEL), @Value provides a concise and flexible approach for externalizing configuration. In this guide, we will cover:

  • Basic usage of @Value

  • Injecting values from properties and system properties

  • Setting default values

  • Auto-mapping to various types (e.g., Duration)

  • Injecting lists and collections

  • Evaluating SpEL expressions

  • Best practices and advanced tips


1. Basic Usage

The simplest use of @Value is to inject a property value from your application's property sources. For example, consider a property defined in application.properties:

daily.limit=100

You can inject this value into your bean as follows:

@Value("${daily.limit}")
private int dailyLimit;

This syntax tells Spring to resolve the daily.limit property from the environment and assign it to the dailyLimit field.


2. Injecting System Properties

Sometimes, you need to inject values directly from system properties rather than a properties file. Spring supports this via SpEL. For example, to inject the system property daily.limit, you can use:

@Value("#{systemProperties['daily.limit']}")
private String dailyLimit;

Both the property placeholder syntax ("${daily.limit}") and the SpEL syntax ("#{systemProperties['daily.limit']}") are valid ways to inject the value of daily.limit. These are the two correct options if you need to access a system property.


3. Setting Default Values

It is a common best practice to provide a default value for configuration properties. This prevents runtime exceptions if the property isn’t defined. You can specify a default value using the colon (:) syntax:

@Value("${daily.limit:50}")
private int dailyLimit;

Here, if daily.limit is not set in any of your property sources, Spring will inject 50 as the default value.


4. Auto-Mapping to Various Types

Spring automatically converts property values from String to the target type of your field, as long as a suitable converter is available. For example:


Mapping to a Duration

If you have a property like this:

app.timeout=PT30S

You can map it directly to a java.time.Duration:

@Value("${app.timeout}")
private Duration timeout;

Spring will convert the ISO-8601 duration string (PT30S) into a Duration object.


Mapping to Other Primitive Types

You can similarly inject values into integers, booleans, doubles, etc.:

@Value("${max.connections:10}")
private int maxConnections;

5. Injecting Lists and Collections

Injecting a list of values can be very useful when you need to configure multiple items. Suppose you have a comma-separated property:

app.servers=server1,server2,server3

You can inject this as a list by leveraging SpEL:

@Value("#{'${app.servers}'.split(',')}")
private List<String> servers;

This expression splits the string by commas and returns a list of server names.


6. Evaluating SpEL Expressions

The @Value annotation also supports the full power of SpEL. You can perform arithmetic, call methods, or even conditionally choose values. For example:


Arithmetic Expression

@Value("#{${daily.limit} * 2}")
private int doubleDailyLimit;

This calculates a new value by multiplying the injected daily.limit by 2.


Conditional Expression

@Value("#{systemProperties['env'] == 'prod' ? 'https://api.prod.example.com' : 'https://api.dev.example.com'}")
private String apiUrl;

This expression selects an API URL based on the value of a system property.


7. Best Practices and Advanced Tips

  • Externalize configuration: Keep your configuration outside of your code by using properties files, environment variables, or system properties.

  • Default values: Always provide defaults to avoid unexpected errors.

  • Type safety: Leverage Spring’s type conversion to auto-map values into the required types.

  • Readability: Use SpEL judiciously. Complex expressions can hurt readability and maintainability.

  • Security: Avoid exposing sensitive information in logs. Securely manage properties such as passwords using encryption or secure vault solutions.


Conclusion

The @Value annotation in Spring is incredibly versatile, allowing you to inject configuration values with minimal fuss. Whether you're working with simple properties, system properties, or evaluating complex expressions, @Value is a key tool in your Spring arsenal. By following the best practices outlined in this guide, you can ensure that your configuration is robust, maintainable, and flexible—helping you build secure and efficient applications.

For further reading, check out the official Spring Framework documentation on Spring Expression Language and configuration management. Happy coding!


Happy Coding!

 
 
 

Comments


bottom of page