Spring Boot’s @Value annotation is a powerful tool for injecting configuration properties into beans. The @Value annotation can be used to inject property values from a variety of sources, including configuration files, environment variables, and command-line arguments.
Here’s an example of how to use the @Value annotation to inject a property value into a bean:
@Component
public class MyBean {
@Value("${my.property}")
private String myProperty;
public void doSomething() {
System.out.println("My property value is: " + myProperty);
}
}
In this example, we’ve annotated our MyBean class with @Component to ensure that it’s picked up by Spring’s component scanning. We’ve also annotated the myProperty field with @Value("$my.property") to inject the value of the my.property property from our configuration files. The value of this property will be stored in the myProperty field, which we can then use in our doSomething() method.
Note that the $my.property syntax is used to specify the property value. The actual value of the property will be determined by the Spring Environment, which can resolve property values from a variety of sources.
You can also use the @Value annotation to inject values from other sources, such as environment variables or command-line arguments. For example, you might use the following syntax to inject an environment variable into a bean:
@Component
public class MyBean {
@Value("\${MY\_ENV\_VAR}")
private String myEnvVar;
public void doSomething() {
System.out.println("My environment variable value is: " + myEnvVar);
}
}
In this example, we’re injecting the value of the MY_ENV_VAR environment variable into our MyBean class using the @Value annotation.
Overall, the @Value annotation is a powerful tool for injecting configuration properties into beans in a Spring Boot application. It can be used to inject values from a variety of sources, and can greatly simplify the process of configuring your application.