java - SPRING beans 中的条件 "ref"

标签 java spring spring-mvc

如果我有类似的东西

<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 postCardimplementsMessageInterfaceclassformalLetterimplementsMessageInterface 并且 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>

最佳答案

我想说你有两个选择。

  1. 使用 Spring Profiles 根据 Activity 配置文件加载其中一个 Bean
  2. 使用 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/

相关文章:

java - 如何从 RequestContextHolder 获取 MultipartHttpServletRequest?

java - 不可变对象(immutable对象)和 Spring/Spring MVC : the right choice?

java - 如何检测不明确的 DST 重叠?

java - 在 Android 中使用相机捕获图像

java - 桌面图形用户界面框架

java - 作为 Gradlew 任务运行时,Mockito Spring 测试失败

java - 更新和删除不适用于 Spring Boot 应用程序

java - 只需单击一下按钮即可连续屏幕切换?

将war部署到tomcat时的Spring MVC Servlet

java - @ModelAttribute注解中声明的Bean的范围是什么