首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring ...loading变量

Spring ...loading变量
EN

Stack Overflow用户
提问于 2014-04-14 04:49:20
回答 1查看 1.4K关注 0票数 0

我的问题如下。

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

例如,

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

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

代码语言:javascript
复制
PrimaryAccount=123
SecondaryAccount=456

现在基于jvm属性值。

代码语言:javascript
复制
// 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> 

但我错了

代码语言:javascript
复制
Field or property '123' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-14 05:01:02

使用以下Java配置

代码语言:javascript
复制
@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不检查“次要”):

代码语言:javascript
复制
<bean class="YourBean">
   <constructor-arg index="0" value="#{systemProperties['instanceId'].equals('primary') ? '456' : '123' }">
</bean>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23052155

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档