SpringBoot中application.yml引入多个YML文件
    		       		warning:
    		            这篇文章距离上次修改已过420天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Boot中,你可以通过使用@PropertySource和@ConfigurationProperties注解来引入多个YML文件。以下是一个简单的例子:
- 创建多个YML文件,例如:application-data.yml,application-feature.yml。
- 在主application.yml文件中引用这些文件:
spring:
  profiles:
    active:
      - data
      - feature- 使用@PropertySource和@ConfigurationProperties来绑定YML文件中的属性到Java类中。
示例代码:
@Configuration
@PropertySource({ "classpath:application-data.yml", "classpath:application-feature.yml" })
@EnableConfigurationProperties(YourProperties.class)
public class YourConfig {
 
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource("application-data.yml"),
                          new ClassPathResource("application-feature.yml"));
        configurer.setProperties(yaml.getObject());
        return configurer;
    }
}
 
@ConfigurationProperties(prefix = "your.prefix")
public class YourProperties {
    // Define your properties here
}请注意,从Spring Boot 2.4开始,YamlPropertiesFactoryBean已被弃用。你可以使用YamlPropertiesLoaderFactory作为替代方案。
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
    YamlPropertiesLoaderFactory loaderFactory = new YamlPropertiesLoaderFactory(data, feature);
    configurer.setProperties(loaderFactory.load());
    return configurer;
}在这个例子中,YourConfig类定义了一个propertySourcesPlaceholderConfigurer方法,它使用YamlPropertiesLoaderFactory加载YAML文件并将它们作为属性源。然后,通过@EnableConfigurationProperties注解,YourProperties类将绑定并加载这些属性。
评论已关闭