spring使用属性文件中的值替换配置文件中的bean名称

时间:2014-04-01 15:40:15

标签: spring

我有一个bean配置文件,如下所示

<bean id="myFactory" class="com.public.Factory">
    <property name="dataSourceAdaptor" ref="${value.from.property file}Adaptor" />
</bean>

我如何实现这一目标。

我在配置文件的顶部添加了以下内容

<util:properties id="myProperties" location="classpath:app.properties"/>

然后尝试使用$ {}引用该值但是我收到一条错误,指出$ {value.from.property file}适配器不是有效的bean

我不能将整个名称(xyzAdaptor)放在属性文件中,因为属性文件中的值是一个机构,并且每个机构都有多个适配器。

例如xzyDisplayAdaptor,xyzProductAdaptor,xyzDatasourceAdaptor

xyz客户端可以更改为说abc客户端,我希望能够将属性文件中的值更改为abc,并且将注入所有与abc相关的bean。

2 个答案:

答案 0 :(得分:1)

util:properties标签用于创建java.util.Properties的实例。我认为你需要的是一个PropertyPlaceholderConfigurer。 如,

<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" scope="singleton">
           <property name="searchSystemEnvironment" value="true" />
           <property name="ignoreResourceNotFound" value="true" />
           <property name="locations">
                <list>
                    <value>classpath:app.properties</value>
                </list>
            </property>
</bean>

答案 1 :(得分:1)

使用Spel尝试:

    <util:properties id="myProperties" location="classpath:app.properties"/>

    <bean id="myFactory" class="com.public.Factory">
        <property name="dataSourceAdaptor" ref="#{'${value.from.property file}'+'Adaptor'}" />
    </bean>