Java SpringXML…有条件地加载变量
我的问题如下 在spring配置中,我希望读取JVM属性。现在,基于JVM属性,我想选择在某个运行时属性中定义的用户名值 比如说, 我定义了一个JVM属性Java SpringXML…有条件地加载变量,java,spring,spring-mvc,jvm,Java,Spring,Spring Mvc,Jvm,我的问题如下 在spring配置中,我希望读取JVM属性。现在,基于JVM属性,我想选择在某个运行时属性中定义的用户名值 比如说, 我定义了一个JVM属性instanceId。它可以有主或次字符串值 另外,我有两个运行时属性 PrimaryAccount=123 SecondaryAccount=456 现在基于jvm属性值 // pseudo code if instanceId = primary Bean ABC should be passed 123 in its cons
instanceId
。它可以有主
或次
字符串值
另外,我有两个运行时属性
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>
使用以下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”,因此不完全等效):
您可能需要查看配置文件,例如,请参阅我只需要为一个属性设置一个简单的开关。不想设置显式文件然后直接传递构造函数arg或用户postconstruct{systemProperties['newsAppIndexDataNode'].equals('primary')?${instance_primary}:${instance_secondary}}你能给我这个xml片段吗???@user1700020在你发布的xml中,你在这两种情况下都选择PrimaryAccount。此外,您还需要将PrimaryAccount设置为XML中的某个属性抱歉,我的错误。。。是的,这些值正在从属性文件中读取。但我得到了额外的报价与价值观
@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
}
}
<bean class="YourBean">
<constructor-arg index="0" value="#{systemProperties['instanceId'].equals('primary') ? '456' : '123' }">
</bean>