如何避免在java文件中硬编码字符串?

时间:2015-08-12 14:13:29

标签: java spring

我正在使用春天。我需要根据String返回对象。我有以下代码。

public class DaoFactoryImpl implements DaoFactory {

    private String dbType;

    private OrganizationActions organizationActions;
    private ProductActions productActions;

    public void setOrganizationActions(OrganizationActions org){
        this.organizationActions = org;
    }

    public void setProductActions(ProductActions prodActions){
        this.productActions = prodActions;
    }

    public void setDbType(String dbType){
        this.dbType = dbType;
    }

    @Override
    public OrganizationActions getDaoObject() {
        if(dbType.equalsIgnoreCase("Oracle")){
            return organizationActions;
         }else if(dbType.equalsIgnoreCase("DB2")){
            return productActions;
         }
        return null;
    }
}

Spring_congig.xml:

<util:properties id="configProps"
        location="classpath:config/config.properties" />

    <bean id="orgService" class="com.sample.OrganizationMongoService">

    </bean>


    <bean id="productService" class="com.sample.ProductMongoService"/>

    <bean id="daoFactory" class="com.sample.factory.DaoFactoryImpl">
        <property name="dbType" value="${dbName}"/>
        <property name="organizationActions" ref="orgService"/>
        <property name="productActions" ref="productService"/>
    </bean>

我在config.properties文件中指定 dbName 。我在DaoFactoryImpl类中硬编码了相同的dbName(Oracle,DB2)。如何在代码中避免硬编码Oracle,DB2。无论如何都要在spring xml文件中指定这个条件吗?

2 个答案:

答案 0 :(得分:2)

尝试在spring配置中创建map并使用它来查找正确的实例。例如:

<bean id="daoFactory" class="com.sample.factory.DaoFactoryImpl">
    <property name="dbType" value="${dbName}"/>
    <property name="typeMap">
        <map>
            <entry key="Oracle" value-ref="orgService"/>
            <entry key="DB2" value-ref="productService"/>
        </map>
    <property>
</bean>

然后在您的工厂方法中进行查找:

public void setTypeMap(Map<String,Actions> typeMap){
    this.typeMap = typeMap;
}

@Override
public OrganizationActions getDaoObject() {
    return typeMap.get(dbType);
}

答案 1 :(得分:0)

您可以在Spring_congig.xml中添加以下代码: -

<bean 
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>properties/database.properties</value>
    </property>
</bean>

并将database.properties中的键值对定义为: -

dbName=Oracle

您的Spring_congig.xml将获取给定密钥所需的值。

 <property name="dbType" value="${dbName}"/>