繁体   English   中英

可选的@PropertySource位置

[英]Optional @PropertySource location

我在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属性( configLocation )时使用的可选.properties 甚至可以使用@PropertySource还是有其他解决方案?

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

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

如果你还没有参加Spring 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) {}
    }

}

请尝试以下方法。 创建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);
    }
  }

上面的代码尝试查找每个活动配置文件的属性文件(请参阅: 如何通过适当的文件而不是通过env变量或系统属性设置活动的spring 3.1环境配置文件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM