Spring Boot uses the @Value annotation to dynamically inject external values into the Bean.

Constant injection

@Value(constant), constants can be strings, files, URLS.

@value ("Hello, Spring Boot") private String Hello; @value ("classpath:config.txt") private Resource Resource; @value ("http://www.baidu.com") private Resource URL;Copy the code

Configuration file value injection

@value (“${config name: default}”), which injects a default Value if no config name exists in the configuration file.

@Value("${location.longitude:unknown}")
private String longitude;
Copy the code

Inject other Bean properties

@value (“#{Bean. Property name? :’ default ‘}”), displays the default value if the value corresponding to the property name is null.

Pay attention toThe default valueThere are single quotes and the attribute name must exist.

@Value("#{beanX.name?:'unknown'}")
private String beanXName;
Copy the code

Inject system properties

@value (“#{systemProperties[‘ systemProperties ‘]? :’ default ‘}”), displays the default value if the system property name does not exist.

@Value("#{systemProperties['os.name']?:'... '}") private String systemPropertiesName;Copy the code

Injected expression result

@value ("#{T(java.lang.math).random() * 100.0}") private double randomNumber;Copy the code