2015-08-28 80 views
0

我在Spring, Java, Ant Web应用程序中工作。我正在使用Spring分析来基于环境加载属性。下面是示例使用Spring配置文件加载环境属性

@Profile("dev") 
@Component 
@PropertySource("classpath:dev.properties") 
public class DevPropertiesConfig{ 

} 
@Profile("qa") 
@Component 
@PropertySource("classpath:qa.properties") 
public class TestPropertiesConfig { 

} 

@Profile("live") 
@Component 
@PropertySource("classpath:live.properties") 
public class LivePropertiesConfig{ 

} 

web.xml中,我们可以给轮廓

<context-param> 
     <param-name>spring.profiles.active</param-name> 
     <param-value>dev</param-value> 
    </context-param> 

现在,我的查询是每一个环境,我需要创建一个单独的Java类。

问:是否有可能只有一个类如提供配置文件名像@Profile({profile})一些有约束力的参数。

另外,让我知道是否有其他更好的选择可用来实现相同。

+0

是的,这是可能的,你做对了。 –

+2

而不是使用基于活动配置文件的'ApplicationContextInitializer'添加指向该配置文件文件的'ResourcePropertySource'。这也是Spring Boot(或多或少)的作用。 –

+0

有关@ M.Deinum答案的详细示例,请参阅此[SO答案](http://stackoverflow.com/a/8601353/3898076)。 –

回答

0

一次可以有多个配置文件处于活动状态,因此没有单个属性可以获取活动配置文件。一个通用的解决方案是创建一个基于活动配置文件的ApplicationContextInitializer加载其他配置文件。

public class ProfileConfigurationInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { 

    public void initialize(final ConfigurableApplicationContext ctx) { 
     ConfigurableEnvironment env = ctg.getEnvironment(); 
     String[] profiles = env.getActiveProfiles(); 
     if (!ArrayUtils.isEmpty(profiles)) { 
      MutablePropertySources mps = env.getPropertySources(); 
      for (String profile : profiles) { 
       Resource resource = new ClassPathResource(profile+".properties"); 
       if (resource.exists()) { 
        mps.addLast(profile + "-properties", new ResourcePropertySource(resource); 
       } 
      } 
     } 
    } 
} 

像这样的事情应该做的伎俩(可能包含错误,因为我从我的头顶键入它)。

现在在您的web.xml中包含一个名为contextInitializerClasses的上下文参数,并为其指定初始值设定项的名称。

<context-param> 
    <param-name>contextInitializerClasses</param-name> 
    <param-value>your.package.ProfileConfigurationInitializer</param-value> 
</context-param> 
相关问题