0
点赞
收藏
分享

微信扫一扫

spring boot中访问YAML配置

捌柒陆壹 2022-12-05 阅读 74


spring:
profiles: dev | test
server:
url: http://localhost
app:
name: MyApplication
threadCount: 4
users:
- A
- B

比如一个这样的YAML,在spring boot中如何访问YAML中的内容呢,首先可以创建带注解@ConfigurationProperties的类

@ConfigurationProperties("server")
@Configuration
@EnableConfigurationProperties
public class ServerProperties {

private String url;

private final App app = new App();

public App getApp() {
return app;
}
//getter and setter for url

public static class App {

private String name;
private String threadCount;
private List<String> users = new ArrayList<>();

//getters and setters
}

}

然后在要使用的类中:

@Service
public class AppService {

@Autowired
private ServerProperties config;

public void printConfigs() {
System.out.println(this.config.getUrl());
System.out.println(this.config.getApp().getName());
System.out.println(this.config.getApp().getThreadCount());
System.out.println(this.config.getApp().getUsers());
}
}

 

举报

相关推荐

0 条评论