February 21, 2022

Spring @Value Annotation

Spring @Value annotation at the field or method/constructor parameter level is used to inject a value. @Value annotation in Spring can be used in the following ways-

  1. Directly to inject a value at the field, method or constructor level.
  2. Using @Value annotation you can also assign a value by reading it from a properties file or you can also read a system property.
  3. You can also use this annotation with a SpEL expression to get the value.

Spring @Value annotation to inject value

You can assign a default value to a field. Though the annotation takes only String type as value but it can convert it to the appropriate type.

@Component
public class Person {
  @Value("SomeName")
  private String name;
  @Value("999")
  private int age;
  @Value("true")
  private boolean flag;
  ..
  ..

}

As you can see using @Value annotation value is assigned to int and boolean field too apart from a String field.

@Value annotation with methods

If you use @Value annotation with the method all the arguments will be assigned with the value provided with the annotation.

@Value("hello")
public void displayValues(String a, String b) {
  System.out.println(a);
  System.out.println(b);
}

Here both a and b arguments will have the assigned values as hello.

To avoid that same assignment you can use @Value annotation directly with method parameter.

@Value("hello")
public void displayValues(String a, @Value("World") String b) {
  System.out.println(a);
  System.out.println(b);
}

Now a will have hello as value where as b will have world as value.

Spring @Value with properties file

Injecting values to the fields using @Value by reading them from properties file is a scenario which you may use. To add a Properties file to Spring’s Environment @PropertySource annotation is used.

For example there is db.properties file saved at location /src/main/resources/ so that it is on the classpath and using the values in this properties file you want to configure a Apache DBCP datasource.

db.properties
db.url=jdbc:oracle:thin:@localhost:1521/XEPDB1
db.user=test
db.password=test
db.driver-class-name=oracle.jdbc.driver.OracleDriver
DBConfiguration.java
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration("dbConfig")
@PropertySource(value="classpath:properties/db.properties")
public class DBConfiguration {
  @Value("${db.driver-class-name}")
  private String driverClassName;
  @Value("${db.url}")
  private String url;
  @Value("${db.user}")
  private String userName;
  @Value("${db.password}")
  private String pwd;
    
  @Bean
  public BasicDataSource dataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setUrl(url);
    ds.setUsername(userName);
    ds.setPassword(pwd);
    return ds;
  }
}

Class with main method to run the example.

public class App {
  public static void main(String[] args) {
    AbstractApplicationContext context = new AnnotationConfigApplicationContext(DBConfiguration.class);
    //ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
    BasicDataSource ds = context.getBean("dataSource", BasicDataSource.class);
    System.out.println("Driver class Name- " + ds.getDriverClassName());
    System.out.println("URL- " + ds.getUrl());
    System.out.println("User- " + ds.getUsername());
    context.close();
  }
}
Output
Driver class Name- oracle.jdbc.driver.OracleDriver
URL- jdbc:oracle:thin:@localhost:1521/XEPDB1
User- test
Setting default value

You can also provide a default value for properties that might not be defined in the properties file.

@Value("${db.poolsize:10}")
private int initialPoolSize;

If db.poolsize property is found then the value associated with the property is assigned to the field initialPoolSize otherwise 10 is assigned.

Accessing system variables using @Value annotation

Spring framework reads all the system variables and store them as properties so you can also assign system variables using @Value.

@Value("${username}")
private String userName;

@Value("${number_of_processors}")
private int numberOfProcessors;

@Value("${temp}")
private String temp;

Spring @Value with SpEL

Another use case for the usage of @Value is using it with Spring Expression Language (SpEL).

In SpEL there are two variables "systemProperties" and "systemEnvironment" that allows us to access information from system properties and environment variables.

  • systemProperties– A java.util.Properties object to provide information about the local system.
  • systemEnvironment– A java.util.Properties object retrieving environment specific properties from the OS.

Injecting system properties Java home and user directory.

@Value ("#{systemProperties['java.home']}")
private String javaHome;

@Value ("#{systemProperties['user.dir']}")
private String userDir;
Injecting system environment variables.
@Value("#{ systemEnvironment['USERNAME'] }")
private String userName;

@Value("#{ systemEnvironment['number_of_processors'] ?: '4'}")
private int numberOfProcessors;

@Value("#{systemEnvironment['TEMP'] }")
private String temp;

For other examples using @Value annotation and SpEL please check this post- Spring Expression Language (SpEL) Tutorial

That's all for the topic Spring @Value Annotation. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment