在本快速教程中,我们将学习如何使用YAML文件来配置Spring Boot应用程序的属性。
什么是YAML文件?
除了可以在Spring中没有应用程序.properties之外 ,我们还可以使用application.yml作为配置文件。 YAML是JSON的超集,我们可以将其用于配置数据。 YAML文件更易于阅读,尤其是当我们有许多层次结构配置时。
让我们看看一个非常基本的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键来提及应用了属性值的配置文件。 例如:
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
然后根据活动的弹簧曲线分配属性值。 在运行Spring应用程序时,我们可以将配置文件设置为:
-Dspring.profiles.active=dev
绑定YAML配置:
访问YAML属性的一种方法是使用@Value(“ $ {property}”)批注。 但是,还有另一种流行的方法可以确保强类型的Bean统治并验证我们的应用程序配置。
为此,我们将创建一个@ConfigurationProperties类,该类映射一组相关属性:
@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}}
请注意,我们可以创建一个或多个@ConfigurationProperties类。
现在让我们定义AppConfig类:
@Configuration
@EnableConfigurationProperties(ServerProperties.class)
public class ApplicationConfig {...}
在这里,我们提到了要在@EnableConfigurationProperties批注中注册的属性类的列表。
访问YAML属性:
现在,我们可以通过使用我们创建的@ConfigurationProperties Bean来访问YAML属性。 我们将像注入任何常规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应用程序,并调用ou r printConfigs()方法。 我们的应用程序将根据活动的弹簧轮廓打印出属性值。
结论:
在本教程中,我们学习了如何在Spring Boot应用程序中使用YAML配置文件。
翻译自: https://www.javacodegeeks.com/2019/05/spring-boot-yaml-configuration.html