preface

You can use @ConfigurationProperties to inject configuration into an entire class, while @Value annotations can inject configuration into fields for more fine-grained control.

The source code

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
    String value(a);
}
Copy the code

Note: Fields modified by annotations cannot be static or final.

use

@value (“${}”) is used to load values from external files. @value (“#{}”), used to execute SpEl expressions and assign content to properties.

We can take the value of the property in the Spring Boot configuration file (.yml or.properties) and assign it to the specified variable.

.@Value("${my.config.field}")
privateString value; .Copy the code

SpEL is an expression language that can run statements dynamically. If you use Thymeleaf, you will feel a sense of familiarity.

.@Value("#{1 + 1}")
private Integer value; / / 2.Copy the code