使用spring的条件bean [英] conditional beans using spring

查看:94
本文介绍了使用spring的条件bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试写一个 ValidatorFactory ,它会根据其类型给我一个验证器

I am trying to write a ValidatorFactory which will give me a validator based on its type

public Validator getNewValidator(ValidatorType type){

    switch:
         case a : new Validator1();
         break;
          case b : new Validator2();
        break;

}

我想用spring xml bean定义编写

I want to write using spring xml beans definition

我可以使用方法注入,但它只允许我创建一个对象,而且方法可以

I can use method injection but it will let me create only one object and the method does

不带任何参数。

我不想使用 FactoryBean ..我只是想看看我们是否可以使用spring xml来做到这一点

I don't want to use FactoryBean.. I am just looking whether we can do this using spring xml

bean定义。

推荐答案

你可以用条件bean注入普通的xml。 ref属性可以由属性文件中的属性值触发,从而根据属性值创建条件bean。此功能未记录,但它完美无缺。

you can do conditional bean injection with plain xml. The "ref" attribute can be triggered by property values from a property file and thus create conditional beans depending on property values. This feature is not documented but it works perfect.

<bean id="validatorFactory" class="ValidatorFactory">
<property name="validator" ref="${validatorType}" />
</bean>

<bean id="validatorTypeOne" class="Validator1" lazy-init="true" />
<bean id="validatorTypeTwo" class="Validator2" lazy-init="true" />

属性文件的内容如下:

validatorType = validatorTypeOne

validatorType=validatorTypeOne

要在xml中使用属性文件,只需将此上下文添加到spring config的顶部

To use the property file in your xml just add this context to the top of your spring config

<context:property-placeholder location="classpath:app.properties" />

这篇关于使用spring的条件bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆