必需Spring中相同类型的多个bean

在您将其标记为重复之前的请求。 我已经通过论坛,无法在任何地方找到问题的解决方案。

我正在使用Spring 3.2编写代码,所有内容都是纯粹基于注释的。 代码接收从不同XSD文件派生的XML文件。

所以我们可以说,有五种不同的XSD(A1,A2,A3,A4,A5),我的代码接收任何类型的XML,我有逻辑来识别到达时的XML类型。

现在,我试图使用Spring OXM解组这些。 但由于涉及多个XSD,我们实际上无法使用一个Un-marshaller。 所以我们需要大约五个。

Configuration类中,我添加了五个bean,如下所示:

 @Bean(name="A1Unmarshaller") public Jaxb2Marshaller A1Unmarshaller(){ Jaxb2Marshaller unMarshaller = new Jaxb2Marshaller(); unMarshaller.setContextPath("package name for the classes generate by XSD A1"); } @Bean(name="A2Unmarshaller") public Jaxb2Marshaller A1Unmarshaller(){ Jaxb2Marshaller unMarshaller = new Jaxb2Marshaller(); unMarshaller.setContextPath("package name for the classes generate by XSD A2"); } @Bean(name="A3Unmarshaller") public Jaxb2Marshaller A3Unmarshaller(){ Jaxb2Marshaller unMarshaller = new Jaxb2Marshaller(); unMarshaller.setContextPath("package name for the classes generate by XSD A3"); } @Bean(name="A4Unmarshaller") public Jaxb2Marshaller A4Unmarshaller(){ Jaxb2Marshaller unMarshaller = new Jaxb2Marshaller(); unMarshaller.setContextPath("package name for the classes generate by XSD A4"); } @Bean(name="A5Unmarshaller") public Jaxb2Marshaller A5Unmarshaller(){ Jaxb2Marshaller unMarshaller = new Jaxb2Marshaller(); unMarshaller.setContextPath("package name for the classes generate by XSD A5"); } 

现在我有五个不同的类C1,C2,C3,C4和C5,我试图将一个unmarshaller bean注入一个类。 这意味着A1Unmarshaller将自动连接到C1 ,依此类推。

构建Spring上下文时,它会抛出一个错误,说它期望一个类型为Jaxb2Marshaller bean并获得五个。

注意使用XML配置完成后工作正常,所以我不确定是否遗漏了某些内容。 请帮忙。

编辑其中一个类C1的代码如下:

 @Component public class C1{ @Autowired private Jaxb2Marshaller A1Unmarshaller; A1 o = null public boolean handles(String event, int eventId) { if (null != event&& eventId == 5) { A1 = A1Unmarshaller.unMarshal(event); return true; } return false; } 

}

您应该限定自动assembly变量以说明应该注入哪一个

 @Autowired @Qualifier("A1Unmarshaller") private Jaxb2Marshaller A1Unmarshaller; 

默认自动assembly是按类型而不是按名称,因此当存在多个相同类型的bean时,必须使用@Qualifier注释。

使用@Resource注释进行注入是您正在寻找的。 您可以使用

 @AutoWired @Qualifier("A1Unmarshaller") private Jaxb2Marshaller A1Unmarshaller; 

但这不是唯一的方法。

 @Resource("A1Unmrshaller") 

这份工作也是。 我建议你使用后者! 看看为什么

Jaxb2Marshaller完全能够使用多个不同的上下文/ xsd。 只需使用setContextPaths方法指定多个上下文路径即可。

 @Bean(name="A1Unmarshaller") public Jaxb2Marshaller A1Unmarshaller(){ Jaxb2Marshaller unMarshaller = new Jaxb2Marshaller(); unMarshaller.setContextPaths( "package name for the classes generate by XSD A1", "package name for the classes generate by XSD A2", "package name for the classes generate by XSD A3", "package name for the classes generate by XSD A4", "package name for the classes generate by XSD A5" ); return unMarshaller; } 

这样你只需要一个marshaller / unmarshaller。

链接

  1. Jaxb2Marshaller javadoc
  2. setContextPaths javadoc