Spring xml ...有条件地加载变量

时间:2014-04-14 04:49:21

标签: java spring spring-mvc jvm

我的问题如下。

在我的spring配置中,我想读取一个JVM属性。现在基于JVM属性,我想选择一些运行时属性中定义的用户名值。

例如,

我定义了一个JVM属性instanceId。它可以包含primarysecondary个字符串值。

另外,我有两个运行时属性。

PrimaryAccount=123
SecondaryAccount=456

现在基于jvm属性值。

// pseudo code
if instanceId = primary 
    Bean ABC should be passed 123 in its constructor argument 

if instanceId = secondary 
    Bean ABC should be passed 456 in its constructor argument 



  I am trying this 

<constructor-arg> 
  <value>#{ systemProperties['newsAppIndexDataNode'].equals('primary') ? ${instance_primary} :    ${instance_secondary} }</value> 
</constructor-arg> 

但我收到错误

Field or property '123' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'

1 个答案:

答案 0 :(得分:1)

使用以下Java配置

@Configuration
public class SomeConfig {

   @Autowired
   private Environment environment;

   @Bean
   public YourBeanType yourBeanType() {
       final String jvmProperty = environment.getProperty("instanceId");
       if(jvmProperty.equals("primary")) {
           return new YourBeanType(123);
       }
       else if(jvmProperty.equals("secondary")) {
           return new YourBeanType(456);
       }

       return new YourBeanType(-1); //return whatever is meaningfull here, or throw an exception

   }
}

修改

XML配置可能看起来像这样(不完全相同,因为id不会检查&#39; secondary&#39;):

<bean class="YourBean">
   <constructor-arg index="0" value="#{systemProperties['instanceId'].equals('primary') ? '456' : '123' }">
</bean>