我的问题如下。
在我的spring配置中,我想读取一个JVM属性。现在,基于JVM属性,我希望选择在某些运行时属性中定义的用户名值。
例如,
我有一个JVM属性定义了instanceId。它可以有primary或secondary字符串值。
另外,我有两个运行时属性。
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'发布于 2014-04-14 05:01:02
使用以下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不检查“次要”):
<bean class="YourBean">
<constructor-arg index="0" value="#{systemProperties['instanceId'].equals('primary') ? '456' : '123' }">
</bean>https://stackoverflow.com/questions/23052155
复制相似问题