在Spring Boot中,可以使用@ConfigurationProperties注解來獲取配置文件的值。
application.properties
myapp.name=My Application
myapp.version=1.0
application.yml
myapp:
name: My Application
version: 1.0
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;
}
}
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();
}
}
在上述例子中,MyAppProperties類使用@ConfigurationProperties注解的prefix屬性指定了配置項的前綴,Spring Boot會自動將配置文件中以該前綴開頭的配置項的值綁定到該類的相應屬性上。然后,在MyController類中通過構造函數注入MyAppProperties實例,并使用該實例獲取配置值。