如何更优雅地获取spring boot yml中的值
时间: 2024-04-12 13:28:56 浏览: 26
在Spring Boot中,可以通过使用`@Value`注解来获取`yml`配置文件中的值。下面是一种更优雅的方式,使用`@ConfigurationProperties`注解来获取`yml`中的值:
1. 创建一个配置类,使用`@ConfigurationProperties`注解,并指定前缀,以映射`yml`中的属性。例如:
```java
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {
private String myProperty;
public String getMyProperty() {
return myProperty;
}
public void setMyProperty(String myProperty) {
this.myProperty = myProperty;
}
}
```
2. 在`application.yml`中添加配置项。例如:
```yaml
myapp:
myProperty: Hello World
```
3. 在需要使用配置值的地方,注入配置类并使用对应的属性。例如:
```java
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 myAppProperties;
@Autowired
public MyController(MyAppProperties myAppProperties) {
this.myAppProperties = myAppProperties;
}
@GetMapping("/myproperty")
public String getMyProperty() {
return myAppProperties.getMyProperty();
}
}
```
通过这种方式,你可以更优雅地获取`yml`配置文件中的值,并且可以将相关配置项集中在一个类中,方便管理和使用。