Spring Framework Tutorial

Software Setup and Configuration (STS/Eclipse/IntelliJ)

Core Spring

Spring Annotations

Spring Data

Spring JDBC

Spring Security

Spring @Value Annotation with Example

The @Value annotation in Spring is used to inject values from property files or to inject values directly. It can be applied at the field level or on method parameters to inject values.

Here's an overview of how you can use the @Value annotation in Spring, with an example:

1. Setting up properties

Let's create a properties file named application.properties:

app.name=SampleApp
app.version=1.0

If you're using Spring Boot, you'd typically place this file in the src/main/resources directory.

2. Configuring PropertySourcesPlaceholderConfigurer

If you're using XML-based configuration, you need to register a PropertySourcesPlaceholderConfigurer bean to resolve ${...} placeholders:

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="location">
        <value>classpath:application.properties</value>
    </property>
</bean>

For Java-based configuration (especially in Spring Boot), this step is usually unnecessary since it's handled automatically.

3. Using @Value annotation in a Spring Bean

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class AppConfig {

    @Value("${app.name}")
    private String appName;

    @Value("${app.version}")
    private String appVersion;

    public void printAppDetails() {
        System.out.println("App Name: " + appName);
        System.out.println("App Version: " + appVersion);
    }
}

In the above class, appName and appVersion fields will be populated with the values from the application.properties file due to the @Value annotations.

4. Running the Example

Let's see how you can run the example:

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;

@ComponentScan(basePackages = "com.example") // replace with your package name
@PropertySource("classpath:application.properties")
public class Application {

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
        AppConfig appConfig = context.getBean(AppConfig.class);
        appConfig.printAppDetails();
    }
}

When you run the Application class, it should print:

App Name: SampleApp
App Version: 1.0

This example demonstrates how the @Value annotation fetches values from a properties file and injects them into a Spring bean. It's a very handy feature, especially when you want to externalize configuration details from the actual application code.

  1. Using @Value annotation in Spring:

    • Description: The @Value annotation in Spring is used to inject values into fields or methods in a Spring bean. It supports various sources for providing values, such as property files, system properties, and environment variables.
    • Example Code:
      @Component
      public class MyComponent {
          @Value("${my.property}")
          private String myProperty;
      
          // Rest of the class...
      }
      
  2. Spring @Value annotation example:

    • Description: An example demonstrating the usage of @Value annotation to inject a property value.
    • Example Code:
      @ValueExample
      public class MyComponent {
          @Value("${my.property}")
          private String myProperty;
      
          // Rest of the class...
      }
      
  3. Injecting values with @Value annotation in Spring:

    • Description: Illustrates how to use @Value annotation to inject values from configuration properties.
    • Example Code:
      @Component
      public class MyComponent {
          @Value("${app.name}")
          private String appName;
      
          // Rest of the class...
      }
      
  4. Configuring properties with @Value in Spring:

    • Description: Shows how to configure Spring properties using the @Value annotation.
    • Example Code:
      @Component
      public class MyConfig {
          @Value("${server.port}")
          private int serverPort;
      
          // Rest of the class...
      }
      
  5. Using @Value annotation with Spring Boot:

    • Description: Integration of @Value annotation with Spring Boot, allowing easy externalized configuration.
    • Example Code:
      @SpringBootApplication
      public class MyApp {
          @Value("${app.name}")
          private String appName;
      
          // Rest of the class...
      }
      
  6. Dynamic property values with @Value in Spring:

    • Description: Demonstrates how to use @Value for dynamic property values.
    • Example Code:
      @Component
      public class DynamicComponent {
          @Value("#{systemProperties['user.home']}")
          private String userHome;
      
          // Rest of the class...
      }
      
  7. Customizing property sources with @Value in Spring:

    • Description: Customizing property sources by specifying different locations for property values using @Value.
    • Example Code:
      @PropertySource("classpath:custom.properties")
      @Component
      public class CustomComponent {
          @Value("${custom.property}")
          private String customProperty;
      
          // Rest of the class...
      }
      
  8. Property injection using @Value annotation in Spring:

    • Description: Using @Value for property injection in various Spring components.
    • Example Code:
      @Component
      public class PropertyComponent {
          @Value("${app.version}")
          private String appVersion;
      
          // Rest of the class...
      }
      
  9. Conditional property injection with @Value in Spring:

    • Description: Conditionally injecting properties based on specific conditions using @Value.
    • Example Code:
      @Component
      public class ConditionalComponent {
          @Value("${feature.enabled:false}")
          private boolean featureEnabled;
      
          // Rest of the class...
      }
      
  10. Externalizing configuration with @Value in Spring:

    • Description: Externalizing configuration properties using the @Value annotation.
    • Example Code:
      @Component
      @PropertySource("classpath:external-config.properties")
      public class ExternalConfigComponent {
          @Value("${external.property}")
          private String externalProperty;
      
          // Rest of the class...
      }
      
  11. Injecting environment properties with @Value in Spring:

    • Description: Injecting properties from the environment using @Value.
    • Example Code:
      @Component
      public class EnvironmentComponent {
          @Value("${java.home}")
          private String javaHome;
      
          // Rest of the class...
      }
      
  12. SpEL expressions with @Value annotation in Spring:

    • Description: Using Spring Expression Language (SpEL) expressions within @Value annotation.
    • Example Code:
      @Component
      public class SpELComponent {
          @Value("#{ T(java.lang.Math).random() * 100.0 }")
          private double randomValue;
      
          // Rest of the class...
      }
      
  13. Reading system properties with @Value in Spring:

    • Description: Reading system properties using @Value annotation.
    • Example Code:
      @Component
      public class SystemPropertyComponent {
          @Value("#{systemProperties['user.name']}")
          private String username;
      
          // Rest of the class...
      }
      
  14. Using @Value with default values in Spring:

    • Description: Providing default values with @Value annotation.
    • Example Code:
      @Component
      public class DefaultValueComponent {
          @Value("${undefined.property:default-value}")
          private String propertyWithDefault;
      
          // Rest of the class...
      }
      
  15. Integration of @Value and YAML properties in Spring Boot:

    • Description: Integrating @Value annotation with YAML properties in a Spring Boot application.
    • Example Code:
      # application.yml
      app:
        name: MySpringApp
      
      @SpringBootApplication
      public class MyApp {
          @Value("${app.name}")
          private String appName;
      
          // Rest of the class...
      }
      
  16. Accessing properties in XML configuration with @Value in Spring:

    • Description: Accessing properties using @Value in Spring XML configuration.
    • Example Code:
      <!-- applicationContext.xml -->
      <bean class="com.example.MyComponent">
          <property name="myProperty" value="${my.property}" />
      </bean>
      
  17. Using @Value with profiles in Spring:

    • Description: Configuring properties with profiles using @Value annotation.
    • Example Code:
      @Component
      @Profile("dev")
      public class DevProfileComponent {
          @Value("${dev.property}")
          private String devProperty;
      
          // Rest of the class...
      }
      
  18. Injecting property values into beans with @Value in Spring:

    • Description: Injecting property values into beans using @Value annotation.
    • Example Code:
      @Component
      public class BeanWithProperties {
          @Value("${bean.property}")
          private String beanProperty;
      
          // Rest of the class...
      }