20

I have an application that has 2 beans with the same name, but which are in different packages. My Spring application fails because it cannot decide on which bean to take. Is there any solution for this? The beans do not currently implement specific interfaces.

See below an edited example of the exception:

Caused by:
org.springframework.context.annotation.ConflictingBeanDefinitionException:
Annotation-specified bean name 'dataTransferHandler' for bean class
[aaaaa.ws.handler.DataTransferHandler] conflicts with existing,
non-compatible bean definition of same name and class
[bbbbb.ws.handler.DataTransferHandler]
Lunivore
  • 17,277
  • 4
  • 47
  • 92
Marco
  • 15,101
  • 33
  • 107
  • 174

3 Answers3

24

You will have to give your beans different names - if multiple beans are defined with the same name, then the one defined later will override the one defined earlier - so in your case only one bean will exist with the name of dataTransferHandler.

You can give these two beans different names, so that both can exist and you can inject in the correct one either using: @AutoWired @Qualifier("dataTransferHandler") OR @Resource(name="dataTransferHandler")

Biju Kunjummen
  • 49,138
  • 14
  • 112
  • 125
  • By giving the beans different names you mean changing the class name? – Marco Jun 13 '12 at 13:42
  • 1
    No, the bean name - if you explicitly named it ``, or if you are using annotations `@Service("aName")`. It looks like in your case though the two beans have the same name, they are different types either way right – Biju Kunjummen Jun 13 '12 at 13:57
3

You can give attribute primary="true" to the bean defination you want to have the preference when autowired. But the bean names must be different. There is no solution for same bean name.

At run-time when you will get the autowired class then the primary true bean will get the preference for autowiring. Hope this helps you. Cheers.

Japan Trivedi
  • 4,445
  • 2
  • 23
  • 44
0

I asked another question regarding the same problem, and there is a solution that doesn't require using the @Qualifier annotation: if both of your DataTransferHandler classes have a @Component annotation, you can simply add a String argument to one of their constructions (i.e. @Component("Foo")), and that should solve the problem without needing additional changes.

See User9123's answer on my question for more details.

Dean Gurvitz
  • 854
  • 1
  • 10
  • 24