[英]Conditional “ref” in SPRING beans
如果我有类似的东西
<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中,消息是这样的接口:
MessageInterface message ; // also get; set are here
并且有两个类 - class postCard implements MessageInterface
, class formalLetter implements MessageInterface
并且类HelloWorld
的属性message
必须用postCard bean或formalLetter初始化,如果某个类中的某些值(比如com.askQuestion.ClassWithAConditional)有例如true
价值?
所以if - 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>
我会说你有两个选择。
FactoryBean
在不同的实现之间切换。 使用Spring时,您可以使用配置文件。 在XML声明一个嵌套beans
元件和一套profile
应该在活跃,有效简表可以通过设置来设置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>
有关配置文件的更多信息, 请参阅参考指南 。
您还可以定义一个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>
有关FactoryBean
的更多信息, 请参阅参考指南 。
您可以像这样使用FactoryBean
public class MyFactoryBean implements FactoryBean<MessageInterface>{
private boolean condition;
public void setCondition(boolean condition){ this.condition =condition ; }
public MessageInterface getObject(){
if(condition){return new PostCard();}
else{return new formalLetter();}
}
public Class<MessageInterface> getObjectType() { return MessageInterface.class ; }
public boolean isSingleton() { return false; }
}
然后在您的配置中
<bean class = "MyFactoryBean" id = "myFactoryBean">
<property name = "condition" value ="true"/>
</bean>
<bean id="helloWorld" class="com.askQuestion.HelloWorld">
<property name="message" ref = "myFactoryBean" />
</bean>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.