【问题标题】:Spring, switch property file depending on profileSpring,根据配置文件切换属性文件
【发布时间】:2017-01-25 14:27:43
【问题描述】:

所以我有一个 spring 4 应用程序。 它包含 3 个属性文件:

application.properties
application-dev.properties
application-prod.properties

在 application.properties 的标题中,我指定了我想要的配置文件:

spring.profiles.active=dev

所以在另外两个文件中:

application-dev.properties
application-prod.properties

我在它们之间有重复的条目,所以让我们在开发文件中说我有: host=foo 在产品中我有: host=bar 然后 Spring 根据当前活动的配置文件获取值。 为了告诉 Spring 文件在哪里,我有一个配置类:

@Configuration
@ComponentScan(basePackages = "my.base.package")
@PropertySource({ "classpath:application.properties", "classpath:application-dev.properties", "classpath:application-prod.properties" })
public class ServiceSpringConfiguration
{
  @Bean
  public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer()
  {
    return new PropertySourcesPlaceholderConfigurer();
  }
}

但我注意到,通过这种方式,Spring 从所有文件中加载所有属性并且不允许重复,并且只加载您要求的属性,而不管配置文件如何。 我如何告诉 Spring 根据所选配置文件加载文件? 我本来希望 Spring 扫描文件名并尝试匹配配置文件名称....

顺便说一句,我指的是这样的属性:

@Value("${host}")
  private String       host; 

【问题讨论】:

  • Spring Boot 会为您执行此操作,而普通的 spring 不会。因此,要么使用 Spring Boot,要么使用您自己的机制来构建(附加)属性源。如果您已经在使用 Spring Boot,则删除 @PropertySource 并让 Spring Boot 处理加载(在这种情况下您也不需要 PropertySourcesPlaceholderConfigurer)。
  • 谢谢,我已经实现了接受的答案并且效果很好,但我会看看 Spring Boot 文档,谢谢你的建议,

标签: spring configuration


【解决方案1】:

一个简单的解决方案是使用属性“spring.profiles.active”的值来加载正确的 application.properties。

在你的例子中,它会是这样的:

@Configuration
@ComponentScan(basePackages = "my.base.package")
@PropertySource({ "classpath:application.properties", "classpath:application-${spring.profiles.active}.properties"})
public class ServiceSpringConfiguration

请注意,此解决方案存在问题,因为您可以有多个活动弹簧配置文件,但它不再起作用。

另一种解决方案是通过配置文件创建多个配置类:

@Configuration 
@Profile('dev')
@PropertySource("classpath:application-dev.properties")
public class Devconfiguration {
}

@Configuration 
@Profile('prod')
@PropertySource("classpath:application-prod.properties")
public class Prodconfiguration {
}

【讨论】:

  • 这很好.. 为我节省了很多时间.. 我正在努力加载一个不同名称的属性文件,而 spring 不会自动对其进行分析。
猜你喜欢
  • 1970-01-01
  • 2012-05-27
  • 2018-07-15
  • 2010-12-03
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多