如果我有类似的东西
<bean id="helloWorld" class="com.askQuestion.HelloWorld">
<property name="message" ref = (postCard or formalLetter )if something />
</bean>
...
<bean for postCard class />
<bean for formalLetter class />
在 HelloWorld 类中,消息是这样的接口(interface):
MessageInterface message ; // also get; set are here
有两个类 - class postCardimplementsMessageInterface
和 classformalLetterimplementsMessageInterface
并且 HelloWorld
类中的属性 message
必须使用
postCard bean 或如果某个类中的某些值(例如 com.askQuestion.ClassWithAConditional )具有 true
值,则使用formalLetter?
所以如果 - com.askQuestion.ClassWithAConditional.SendFormalLetter == true;
然后
<bean id="helloWorld" class="com.askQuestion.HelloWorld">
<property name="message" ref = "formalLetterId" />
</bean>
并且如果com.askQuestion.ClassWithAConditional.SendFormalLetter == false;
然后
<bean id="helloWorld" class="com.askQuestion.HelloWorld">
<property name="message" ref = "postCardId" />
</bean>
最佳答案
我想说你有两个选择。
- 使用 Spring Profiles 根据 Activity 配置文件加载其中一个 Bean
- 使用
FactoryBean
在不同的实现之间切换。
个人资料
使用 Spring 时,您可以使用配置文件。在 xml 中声明一个嵌套的 beans
元素并设置它应该在哪个 profile
中处于 Activity 状态。可以通过设置 spring.profiles.active
属性。
<beans ...>
<bean id="helloWorld" class="com.askQuestion.HelloWorld">
<property name="message" ref="messageBean" />
</bean>
<beans profile="postcard">
<bean id="messageBean" class="PostcardBean" />
<beans>
<beans profile="letter">
<bean id="messageBean" class="LetterBean" />
</beans>
</beans>
有关配置文件的更多信息位于 the reference guide .
FactoryBean
您还可以定义 FactoryBean
它会根据您的情况选择要使用的正确 bean。
public class MessageFactoryBean implements FactoryBean<MessageInterface> {
private MessageInterface postcard;
private MessageInterface letter;
public MessageInterface getObject() {
if (your condition here) {
return letter;
}
return postcard;
}
// other methods omitted
}
<beans ...>
<bean id="messageBean" class="MessageFactoryBean">
<property name="postcard">
<bean class="PostcardBean" />
</property>
// other properties omitted
</bean>
<bean id="helloWorld" class="com.askQuestion.HelloWorld">
<property name="message" ref="messageBean"/>
</bean>
</beans>
有关 the reference guide 中的 FactoryBean
的更多信息.
关于java - SPRING beans 中的条件 "ref",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34679026/