在工厂模式中弹出多个具有相同ID的bean?

时间:2014-07-31 07:21:08

标签: spring factory spring-data-neo4j

我有两个与其内部映射到的Neo4j类具有相同ID的bean,因此我无法更改两者的ID。现在对于集群环境,我需要这个bean:

<bean id="graphDatabaseService" factory-bean="graphDbBuilderFinal"
        factory-method="newGraphDatabase" destroy-method="shutdown" /> 

对于非群集的我需要这个:

<bean id="graphDatabaseService" class="org.springframework.data.neo4j.support.GraphDatabaseServiceFactoryBean"
        destroy-method="shutdown" scope="singleton">
<constructor-arg value="${neo4j.database.path}" />
</bean>

现在我根据环境评论其中一个,因为并非所有环境都有集群设置。有没有一种方法可以根据环境值(属性可能)在这些中选择一个bean。

这是在java类中使用它的方式。

@Autowired
private GraphDatabaseService graphDB;

谢谢,

2 个答案:

答案 0 :(得分:4)

您可以使用弹簧配置文件功能(自弹簧3.1.X开始)see link

e.g

<beans profile="cluster">
<bean id="graphDatabaseService" factory-bean="graphDbBuilderFinal"
        factory-method="newGraphDatabase" destroy-method="shutdown" /> 
</beans>

<beans profile="no_cluster">
<bean id="graphDatabaseService" class="org.springframework.data.neo4j.support.GraphDatabaseServiceFactoryBean"
        destroy-method="shutdown" scope="singleton">
<constructor-arg value="${neo4j.database.path}" />
</bean>
</beans>

以这种方式激活应用程序中的配置文件

-Dspring.profiles.active="cluster"

仅加载没有配置文件的bean以及激活配置文件的所有bean。 我希望这个解决方案有助于解决您的问题。

答案 1 :(得分:2)

您不需要在不同的xml配置文件中使用不同的Id进行定义。像

cluster.xml ---&gt;

  <bean id="graphDatabaseService" factory-bean="graphDbBuilderFinal"
    factory-method="newGraphDatabase" destroy-method="shutdown" /> 

no_cluster.xml

  <bean id="graphDatabaseService" class="org.springframework.data.neo4j.support.GraphDatabaseServiceFactoryBean"
    destroy-method="shutdown" scope="singleton">

然后使用Spring配置文件加载一个或另一个文件,具体取决于配置文件

        <beans profile="cluster">
    <import resource="spring/cluster.xml" />
</beans>
<beans profile="no_cluster">
   <import resource="spring/no_cluster.xml" />
</beans>
相关问题