Required Multiple beans of same type in Spring Required Multiple beans of same type in Spring xml xml

Required Multiple beans of same type in Spring


You should qualify your autowired variable to say which one should be injected

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

The default autowiring is by type, not by name, so when there is more than one bean of the same type, you have to use the @Qualifier annotation.


The Jaxb2Marshaller is perfectly capable to work with multiple different contexts/xsd. Simply specify multiple context paths by using the setContextPaths methods.

@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;}

That way you only need a single marshaller/unmarshaller.

Links

  1. Jaxb2Marshaller javadoc
  2. setContextPaths javadoc


Injection using @Resource annotation is what you're looking for. You can use

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

But that is not the only way.

@Resource("A1Unmrshaller")

Does the job too. I suggest you use the later one! See why