Spring @Value Annotation Guide

In Java, the @Value annotation can be used to inject values from an external properties file into Spring beans. When using this annotation, you first need to specify the path to the external properties file using the @PropertySource annotation in the Spring configuration file, and then use the @Value annotation to specify the key value in the properties file where the injection is needed.

For example, consider a properties file called application.properties with the following content:

app.name=MyApp
app.version=1.0

Then specify the path of the file in the Spring configuration file.

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {

}

Next, use the @Value annotation in the places where values need to be injected.

@Component
public class MyApp {

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

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

    // 省略其它代码
}

During runtime, Spring will load external property files based on the file path specified in the @PropertySource annotation, and inject the corresponding values into the appName and appVersion variables in the MyApp class.

bannerAds