Spring 配置中的条件语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6906863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Conditional statement inside Spring config
提问by broun
How to have conditional statement within a spring configuration file
如何在 spring 配置文件中包含条件语句
I have String bean (b) whose value depends on the value of a property (a). a is set dynamically based on environment it runs.
我有 String bean (b),其值取决于属性 (a) 的值。a 是根据它运行的环境动态设置的。
if (a)
b="yes"
else
b="no"
How do i code this in spring config?
我如何在 spring 配置中对此进行编码?
回答by denis.solonenko
As Ryan said SpELcan help. You should be able to do something like this in Spring xml:
正如瑞安所说,SpEL可以提供帮助。你应该能够在 Spring xml 中做这样的事情:
<bean id="flag" class="java.lang.Boolean">
<constructor-arg value="#{ systemProperties['system.propery.flag'] ?: false }" />
</bean>
<bean id="bean" class="com.my.MyBean">
<property name="property" value="#{ flag ? 'yes' : 'no' }"/>
</bean>
回答by Ryan Stewart
See Spring Expression Languagefor Spring 3+. Otherwise, you're probably stuck with writing a FactoryBeanor something similar.
请参阅Spring 3+ 的Spring 表达式语言。否则,您可能会坚持编写FactoryBean或类似的东西。
回答by RAHUL ROY
Try this...It works.. Given Roll,Location,name is in property file and I am reading it above this line.
试试这个......它有效......鉴于滚动,位置,名称在属性文件中,我正在此行上方阅读它。
<bean id="Student" class="beans.Student">
<property name="name" value="#{ ${Roll}== 1 ? '${Location}' : '${name}' }"/>
</bean>
<bean id="Student" class="beans.Student">
<property name="name" value="#{ ${Roll}== 1 ? '${Location}' : '${name}' }"/>
</bean>
回答by Yogi Lal Singh
below is working for me. system property passed as java -Dflag=true -jar project.jar
下面是对我来说有效。系统属性作为 java -Dflag=true -jar project.jar 传递
<bean id="flag" class="java.lang.Boolean">
<constructor-arg value="#{ systemProperties['flag'] ?: false }" />
</bean>
<bean id="bean" class="com.my.MyBean">
<property name="property" value="#{ flag ? 'yes' : 'no' }"/>
</bean>

