Spring PropertySourcesPlaceholderConfigurer和Environment

时间:2016-06-20 19:24:45

标签: java spring properties

我想为不同的配置文件(生产和开发)配置属性。

这是我的配置:

@Configuration
public class PropertyPlaceholderConfig {

  @Profile(Profiles.PRODUCTION)
  static class ProductionConfiguration {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigure()
    throws IOException {
      PropertySourcesPlaceholderConfigurer propertySources =
      new PropertySourcesPlaceholderConfigurer();
      propertySources.setIgnoreUnresolvablePlaceholders(Boolean.TRUE);
      Resource[] resources =
      ObjectArrays.concat(getCommonResources(), getProductionResources(), Resource.class);
      propertySources.setLocations(resources);
      return propertySources;
    }

    private static Resource[] getProductionResources() throws IOException {
      return new PathMatchingResourcePatternResolver()
      .getResources("classpath:properties/production/*.properties");
    }

  }


  @Profile(Profiles.DEV)
  static class DevConfiguration {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigure()
    throws IOException {
      PropertySourcesPlaceholderConfigurer propertySources =
      new PropertySourcesPlaceholderConfigurer();
      propertySources.setIgnoreUnresolvablePlaceholders(Boolean.TRUE);
      Resource[] resources =
      ObjectArrays.concat(getCommonResources(), getDevResources(), Resource.class);
      propertySources.setLocations(resources);
      return propertySources;
    }

    private static Resource[] getDevResources() throws IOException {
      return new PathMatchingResourcePatternResolver()
      .getResources("classpath:properties/dev/*.properties");
    }

  }


  private static Resource[] getCommonResources() throws IOException {
    return new PathMatchingResourcePatternResolver()
    .getResources("classpath:properties/common/*.properties");
  }


}

我打印了当前配置文件(dev)和加载的文件(所有文件都已正确加载到Resouce数组中)。我想在数据库配置中使用这个加载的属性。怎么做? 我用过:

@Import(PropertyPlaceholderConfig.class)
在课堂上, 和

@Autowired
private Environment environment;

environment.getProperty("h2.driverClass");

environment.resolvePlaceholders("${h2.driverClass}");

不起作用。

如何使用PropertySourcesPlaceholderConfigurer加载的属性?

我知道我可以在字段中使用@Value但是可以避免创建15个字段吗?

0 个答案:

没有答案