Spring @Value Annotation with Example - RameshMF/spring-boot-developers-guide GitHub Wiki

In this article, we will discuss how to inject property values into beans using Spring @Value annotation.

@Value Annotation Overview

This annotation can be used for injecting values into fields in Spring-managed beans and it can be applied at the field or constructor/method parameter level.

A common use case is to assign default field values using "#{systemProperties.myProp}" style expressions.

Setting up the Application

  1. Create property file such as application.properties

Example: Lets assume we are configuring JDBC propeties in application.properties file.

jdbc.url=jdbc:mysql://localhost/EMP
jdbc.username=root
jdbc.password=root
jdbc.driver=com.mysql.jdbc.Driver
  1. Define a @PropertySource in our configuration class – with the properties file name. Example:
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;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

@Configuration
@PropertySource(value = { "classpath:application.properties" })
public class Application {

	@Value("${jdbc.url}")
	private String url;

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

	@Value("${jdbc.password}")
	private String password;

	@Bean
	public DataSource dataSource() {
		return new DriverManagerDataSource(url, username, password);
	}
}

More Usage Examples