简体   繁体   English

在春季,如何定义两个具有相同名称和不同类的Bean

[英]In Spring, How to Define Two Beans, with Same Name and Different Class

I have a java project, using Spring. 我有一个使用Spring的Java项目。 I have defined three classes: BaseClass, SubClass1 and SubClass2. 我定义了三个类:BaseClass,SubClass1和SubClass2。 Two SubClassx both extend BaseClass. 两个SubClassx都扩展了BaseClass。 Now, I need to define two beans, one is in a specific profile: 现在,我需要定义两个bean,一个在特定的配置文件中:

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

and

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

they are in different xml files. 它们位于不同的xml文件中。 I use lombok to inject SubClass2 newBean in a Class: 我使用lombok将SubClass2 newBean注入到一个类中:

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

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

But when I run the project with profile "xxx", it throws: 但是,当我使用配置文件“ xxx”运行该项目时,它将引发:

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

It seems that fail to overwrite bean newBean with SubClass2, even though I have activated profile "xxx". 即使我已激活概要文件“ xxx”,似乎也无法用SubClass2覆盖bean newBean。 Is there any way to use profile, to define two beans, with same name and different class? 有没有什么方法可以使用profile来定义两个具有相同名称和不同类的bean?

Thank you very much. 非常感谢你。

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

I put 我放

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

and

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

in one xml file, and it works. 在一个xml文件中,它可以工作。 But I'd like to separate them into two xml files, according to the project organization. 但是根据项目组织,我想将它们分为两个xml文件。 Any solutions to implement this? 有什么解决方案可以实现吗?

Try using same name instead of id. 尝试使用相同的名称而不是ID。

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

Try restricting the first bean to the default profile 尝试将第一个bean限制为默认配置文件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM