我的问题如下。

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

例如,

我有一个instanceId定义的JVM属性。它可以具有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'

最佳答案

使用以下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不检查“ secondary”,所以不完全等效):

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

10-04 15:49