javascript
Spring Boot YAML配置
在本快速教程中,我們將學(xué)習(xí)如何使用YAML文件來配置Spring Boot應(yīng)用程序的屬性。
什么是YAML文件?
除了可以在Spring中沒有應(yīng)用程序.properties之外 ,我們還可以使用application.yml作為配置文件。 YAML是JSON的超集,我們可以將其用于配置數(shù)據(jù)。 YAML文件更易于閱讀,尤其是當我們有許多層次結(jié)構(gòu)配置時。
讓我們看看一個非常基本的YAML文件是什么樣的:
src / main / resources / application.yml
server:url: http://localhost myapp:name: MyApplicationthreadCount: 4 ...上面的YAML文件等效于下面的application.properties文件:
server.url=http://localhost server.myapp.name=MyApplication server.myapp.threadCount=4 ...Spring使用SnakeYAML來解析YAML文件,該文件在spring-boot-starter中可用:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><version>2.1.5.RELEASE</version> </dependency>我們可以在Maven存儲庫中查看此依賴項的最新版本。
YAML中的Spring配置文件:
我們可以使用spring.profiles鍵來提及應(yīng)用了屬性值的配置文件。 例如:
spring:profiles: dev | test server:url: http://localhost app:name: MyApplicationthreadCount: 4users: - A- B ---- spring:profiles: prod server:url: http://myapp.org app:name: MyApplicationthreadCount: 10users: - Jacob- James然后根據(jù)活動的彈簧曲線分配屬性值。 在運行Spring應(yīng)用程序時,我們可以將配置文件設(shè)置為:
-Dspring.profiles.active=dev綁定YAML配置:
訪問YAML屬性的一種方法是使用@Value(“ $ {property}”)批注。 但是,還有另一種流行的方法可以確保強類型的Bean統(tǒng)治并驗證我們的應(yīng)用程序配置。
為此,我們將創(chuàng)建一個@ConfigurationProperties類,該類映射一組相關(guān)屬性:
@ConfigurationProperties("server") public class ServerProperties {private String url;private final App app = new App();public App getApp() {return app;}//getter and setter for urlpublic static class App {private String name;private String threadCount;private List<String> users = new ArrayList<>();//getters and setters}}請注意,我們可以創(chuàng)建一個或多個@ConfigurationProperties類。
現(xiàn)在讓我們定義AppConfig類:
@Configuration @EnableConfigurationProperties(ServerProperties.class) public class ApplicationConfig {...}在這里,我們提到了要在@EnableConfigurationProperties批注中注冊的屬性類的列表。
訪問YAML屬性:
現(xiàn)在,我們可以通過使用我們創(chuàng)建的@ConfigurationProperties Bean來訪問YAML屬性。 我們將像注入任何常規(guī)Spring bean一樣注入這些屬性bean:
@Service public class AppService {@Autowiredprivate 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());} }然后,我們可以使用AppRunner來啟動我們的Spring應(yīng)用程序,并調(diào)用ou r printConfigs()方法。 我們的應(yīng)用程序?qū)⒏鶕?jù)活動的彈簧輪廓打印出屬性值。
結(jié)論:
在本教程中,我們學(xué)習(xí)了如何在Spring Boot應(yīng)用程序中使用YAML配置文件。
翻譯自: https://www.javacodegeeks.com/2019/05/spring-boot-yaml-configuration.html
總結(jié)
以上是生活随笔為你收集整理的Spring Boot YAML配置的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 克莉丝汀翡翠卡怎么用 使用卡的方法
- 下一篇: Spring与Rails的jQuery