Spring

Spring @Value Annotation

Introduction:

Spring @Value annotation is used to inject values into variables and method arguments. We can either read spring environment variables or system variables. It also supports SpEL.

In this quick tutorial, we’ll explore how to work with Spring @Value annotation.

Setup:

Let’s start by first defining a few properties in our app.properties file:

These are the properties we’ll use for examples throughout this tutorial.

Also, let’s quickly define our AppConfiguration class:

Spring @Value – Basics:

We can assign a default value to a class property with @Value annotation:

Note that it accepts only a String argument but the passed-in value gets converted to an appropriate type during value-injection.

Reading Spring Environment Variables:

We can use @Value annotation to read a Spring environment variable:

We can also read a list of values:

Let’s now try to read a map of values ‘products.count’ using @Value annotation:

To get a value of a specific key from the map, we’ll use:

Reading System Variables:

With Spring @Value, we can also read the system variables, either directly:

Or using SpEL:

Assigning Default Value:

What if we wish to assign a default value in case of a missing property? Yes, we can do it using Spring @Value annotation’s default construct:

Here, the default value of 30 will be assigned to stockCount only if the property ‘user.stocks’┬áis missing from the property file.

We can also assign a default value when working with SpEL:

Injecting Values In Methods:

Apart from the field-based injection, we can also use @Value annotation over a method:

If we use @Value annotation over a method, all of its arguments will get mapped to the same value.

If we want to inject different parameters to different arguments, we can use @Value annotation along with method arguments:

Conclusion:

In this tutorial, we explored different ways in which we can use @Value annotation to inject property values. We can use @Value annotation either with a field or a method.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *