可选的@PropertySource位置

时间:2013-07-01 09:52:05

标签: java spring spring-annotations

我在Web应用程序中使用Spring 3.2,并且我希望在类路径中包含一个包含默认值的.properties文件。用户应该能够使用JNDI来定义存储另一个.properties的位置,该位置将覆盖默认值。

只要用户将configLocation设置为JNDI属性,就可以使用以下命令。

@Configuration
@PropertySource({ "classpath:default.properties", "file:${java:comp/env/configLocation}/override.properties" })
public class AppConfig
{
}

但是,外部覆盖应该是可选的,JNDI属性也应该是可选的。

目前,我在缺少JNDI属性时遇到异常(java.io.FileNotFoundException: comp\env\configLocation\app.properties (The system cannot find the path specified)

如何定义仅在设置JNDI属性(.properties)时使用的可选configLocation?甚至可以使用@PropertySource或是否有其他解决方案?

3 个答案:

答案 0 :(得分:39)

截至4月4日,问题SPR-8371已经解决。因此,@PropertySource注释具有一个名为ignoreResourceNotFound的新属性,该属性已添加用于此目的。此外,还有新的@PropertySources注释,允许实现如下:

@PropertySources({
    @PropertySource("classpath:default.properties"),
    @PropertySource(value = "file:/path_to_file/optional_override.properties", ignoreResourceNotFound = true)
})

答案 1 :(得分:5)

如果你还没有参加第4季(参见matsev的解决方案),这里有一个更详细,但大致相当的解决方案:

@Configuration
@PropertySource("classpath:default.properties")
public class AppConfig {

    @Autowired
    public void addOptionalProperties(StandardEnvironment environment) {
        try {
            String localPropertiesPath = environment.resolvePlaceholders("file:${java:comp/env/configLocation}/override.properties");
            ResourcePropertySource localPropertySource = new ResourcePropertySource(localPropertiesPath);
            environment.getPropertySources().addLast(localPropertySource);
        } catch (IOException ignored) {}
    }

}

答案 2 :(得分:3)

尝试以下方法。创建ApplicationContextInitializer

在Web上下文中:ApplicationContextInitializer<ConfigurableWebApplicationContext>并通过以下方式在web.xml中注册:

<context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>...ContextInitializer</param-value>
</context-param>

在ContextInitializer中,您可以通过类路径和文件系统添加属性文件(虽然没有尝试过JNDI)。

  public void initialize(ConfigurableWebApplicationContext applicationContext) {
    String activeProfileName = null;
    String location = null;

    try {
      ConfigurableEnvironment environment = applicationContext.getEnvironment();
      String appconfigDir = environment.getProperty(APPCONFIG);
      if (appconfigDir == null ) {
        logger.error("missing property: " + APPCONFIG);
        appconfigDir = "/tmp";
      }
      String[] activeProfiles = environment.getActiveProfiles();

      for ( int i = 0; i < activeProfiles.length; i++ ) {
        activeProfileName = activeProfiles[i];
        MutablePropertySources propertySources = environment.getPropertySources();
        location = "file://" + appconfigDir + activeProfileName + ".properties";
        addPropertySource(applicationContext, activeProfileName,
                location, propertySources);
        location = "classpath:/" + activeProfileName + ".properties";
        addPropertySource(applicationContext, activeProfileName,
                          location, propertySources);
      }
      logger.debug("environment: '{}'", environment.getProperty("env"));

    } catch (IOException e) {
      logger.info("could not find properties file for active Spring profile '{}' (tried '{}')", activeProfileName, location);
      e.printStackTrace();
    }
  }

  private void addPropertySource(ConfigurableWebApplicationContext applicationContext, String activeProfileName,
                                 String location, MutablePropertySources propertySources) throws IOException {
    Resource resource = applicationContext.getResource(location);
    if ( resource.exists() ) {
      ResourcePropertySource propertySource = new ResourcePropertySource(location);
      propertySources.addLast(propertySource);
    } else {
      logger.info("could not find properties file for active Spring profile '{}' (tried '{}')", activeProfileName, location);
    }
  }

上面的代码尝试查找每个活动配置文件的属性文件(请参阅:How to set active spring 3.1 environment profile via a properites file and not via an env variable or system property