How can Spring Boot retrieve values from configuration files?
In Spring Boot, you can utilize the @ConfigurationProperties annotation to access values from configuration files.
- Define configuration options in the application.properties or application.yml file, for example:
properties file for the application
myapp.name=My Application
myapp.version=1.0
config.yml
myapp:
name: My Application
version: 1.0
- Create a configuration class and use the @ConfigurationProperties annotation to bind configuration properties, for example:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {
private String name;
private String version;
// 省略getter和setter方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
- In places where configuration values are needed, obtain an instance of the configuration class through dependency injection.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
private final MyAppProperties appProperties;
@Autowired
public MyController(MyAppProperties appProperties) {
this.appProperties = appProperties;
}
@GetMapping("/app-info")
public String getAppInfo() {
return appProperties.getName() + " " + appProperties.getVersion();
}
}
In the example above, the class MyAppProperties specifies the prefix attribute using the @ConfigurationProperties annotation, which tells Spring Boot to automatically bind the values of configuration items that start with this prefix in the configuration file to the corresponding properties in this class. Subsequently, in the MyController class, an instance of MyAppProperties is injected through the constructor and used to retrieve configuration values.