在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实例,并使用该实例获取配置值。