在Spring中,如何定义两个具有相同名称和不同类别的Bean

时间:2016-11-11 03:28:13

标签: java spring javabeans profile

我有一个使用Spring的java项目。我定义了三个类:BaseClass,SubClass1和SubClass2。两个SubClassx都扩展了BaseClass。 现在,我需要定义两个bean,一个在特定的配置文件中:

<bean id="newBean" class="SubClass1">

<beans profile="xxx">
    <bean id="newBean" class="SubClass2">
</beans>

它们位于不同的xml文件中。我使用lombok在Class:

中注入SubClass2 newBean
public class WarmUpAgent extends WarmUpAgent {
    @Setter(onMethod = @__(@Required))
    private SubClass2 subClass2;
...

<bean id="warmUpAgent" class="WarmUpAgent">
    <property name="subClass2" ref="newBean" />
</bean>

但是当我使用配置文件“xxx”运行项目时,它会抛出:

IllegalStateException: Cannot convert value of type [SubClass1] to required type [SubClass2] for property 'subClass2'

似乎无法用SubClass2覆盖bean newBean,即使我已经激活了配置文件“xxx”。有没有办法使用profile,来定义两个具有相同名称和不同类的bean?

非常感谢。

=============================================== =========================

我把

<bean id="newBean" class="SubClass1">

<beans profile="xxx">
    <bean id="newBean" class="SubClass2">
</beans>

在一个xml文件中,它可以工作。但根据项目组织的说法,我想将它们分成两个xml文件。有任何解决方案可以实现吗?

2 个答案:

答案 0 :(得分:0)

尝试使用 同名 而不是id。

<bean name="newBean" class="SubClass1">
<beans profile="xxx">
    <bean name="newBean" class="SubClass2">
</beans>

答案 1 :(得分:0)

尝试将第一个bean限制为默认配置文件

<beans profile="default">
  <bean id="newBean" class="SubClass1">
</beans>
<beans profile="xxx">
   <bean id="newBean" class="SubClass2">
</beans>