What are the scenarios where @Value is used in Spring?

In Spring, the @Value annotation can be used for property injection. Its use cases include:

  1. Injecting basic type property values: You can use the @Value annotation to inject property values from a configuration file into a Spring Bean. For example:
@Value("${jdbc.url}")
private String url;
  1. Injecting property values of object types: You can use the @Value annotation to inject property values from the configuration file into a custom class. For example:
@Value("#{configProperties}")
private ConfigProperties configProperties;
  1. Injecting system properties: you can inject JVM system properties using the @Value annotation.
    For example:
@Value("#{systemProperties['java.home']}")
private String javaHome;
  1. Injecting environment variables: You can inject operating system environment variables using the @Value annotation.
    For example:
@Value("#{systemEnvironment['PATH']}")
private String path;
  1. The result of injecting SpEL expressions can be obtained by using the @Value annotation to inject the calculation result of the SpEL expression. For example:
@Value("#{T(java.lang.Math).random() * 100.0}")
private double randomNumber;

In general, the @Value annotation is used in Spring for property injection, allowing you to inject values from configuration files, system properties, environment variables, etc. into Spring Beans.

bannerAds