Skip to main content
 首页 » 编程设计

Spring YAML配置

2022年07月19日128lautakyan007

Spring YAML配置

使用yaml配置文件是Spring多种配置方式之一,本文介绍使用yaml配置Spring boot多种profile。

1. Spring YAML文件

Spring profile可以让Spring应用针对不同环境定义不同的属性。下面是一个简单yaml文件包括两个profile,三个横杠分离两个profile,表示下一个profile开始,所有profile可以在相同yaml文件中描述。application.yml文件的相对路径为:

/myApplication/src/main/resources/application.yml.

Spring应用让yaml文件中第一个profile作为缺省profile,除非有其他声明。

spring: 
	profiles: test 
name: test-YAML 
environment: test 
servers:  
    - www.abc.test.com 
    - www.xyz.test.com 
  
--- 
spring: 
    profiles: prod 
name: prod-YAML 
environment: production 
servers:  
    - www.abc.com 
    - www.xyz.com 

2. 配置类绑定yaml文件

为了从属性文件中加载一组相关属性,这里先创建bean类:

@Configuration 
@EnableConfigurationProperties 
@ConfigurationProperties 
public class YAMLConfig {
    
  
    private String name; 
    private String environment; 
    private List<String> servers = new ArrayList<>(); 
  
    // standard getters and setters 
  
} 

这里用到得注解说明:

  • @Configuration 标记该类作为bean定义的配置类
  • @ConfigurationProperties 给配置类绑定外部配置
  • @EnableConfigurationProperties 启用Spring应用中 有*@ConfigurationProperties* 注解的bean

3. 访问yaml属性

为了访问yaml属性,先创建 YAMLConfig类的对象,然后通过对象访问其属性。

在属性文件中,让我们设置 spring.active.profiles环境变量为 prod。如果没有定义spring.active.profiles,那么yaml中的第一个profile为缺省配置。属性文件的相对路径为:

/myApplication/src/main/resources/application.properties.

spring.profiles.active=prod 

下面示例直接使用CommandLineRunner显示属性:

@SpringBootApplication 
public class MyApplication implements CommandLineRunner {
    
  
    @Autowired 
    private YAMLConfig myConfig; 
  
    public static void main(String[] args) {
    
        SpringApplication app = new SpringApplication(MyApplication.class); 
        app.run(); 
    } 
  
    public void run(String... args) throws Exception {
    
        System.out.println("using environment: " + myConfig.getEnvironment()); 
        System.out.println("name: " + myConfig.getName()); 
        System.out.println("servers: " + myConfig.getServers()); 
    } 
} 

命令行输出如下:

using environment: production 
name: prod-YAML 
servers: [www.abc.com, www.xyz.com] 

yaml属性优先级

Spring boot中,yaml文件能够被其他位置的yaml文件覆盖,也能被其他位置中的属性文件覆盖,优先级顺序为:

  • Profiles 属性文件位于jar包外面
  • Profiles 属性文件位于jar包里面
  • application 属性文件位于jar包外面
  • application 属性文件位于jar包里面

4. 总结

本文介绍了Spring boot应用中如何使用yaml配置属性,同时也提及yaml文件的属性覆盖规则。


本文参考链接:https://blog.csdn.net/neweastsun/article/details/108814341