spring boot中访问YAML配置

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/jackyrongvip/article/details/91350098
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());
    }
}

 

展开阅读全文

没有更多推荐了,返回首页