0

In module1.jar:

<bean id="customerService" class="com.service.CustomCustomerServiceImpl" > </bean>

In module2.jar:

<bean id="customerService" class="com.service.CustomerServiceImpl" > </bean>


public class CustomerController {
    @Autowired
    protected CustomerService customerService;

// getters and setters  
}

I see CustomerService is injected with CustomCustomerServiceImpl always.

My question is should an exception be thrown while starting the server since there are two beans (CustomCustomerServiceImpl and CustomerServiceImpl) of type CustomerService.

Should not spring throw exception?

How spring is able to resolve the autowire annotation by type here when multiple beans are found?

Update :-

public class CustomCustomerServiceImpl extends CustomerServiceImpl {}
user3198603
  • 5,528
  • 13
  • 65
  • 125
  • 1
    As you have set an `id` for each bean, Spring will try to match a bean `id` to the name of the attribute you're injecting into. Hence you will always inject `customerService`, as that's the name of your class attribute. If you didn't set an `id` for the beans then yes, you would likely get an exception. – icabod Oct 31 '16 at 15:35
  • @icabod both id's are same. so how `CustomCustomerServiceImpl` is getting injected instead of error ? – user3198603 Oct 31 '16 at 15:38
  • The id's weren't the same a few minutes ago, and one of your beans had the other as a parent, meaning it _possibly_ overrides the base bean. – icabod Oct 31 '16 at 15:39
  • id's were same since beginning in both modules. – user3198603 Oct 31 '16 at 15:42

1 Answers1

0

Should not spring throw exception ? How spring is able to resolve autowire by type here when multiple beans are found ?

If some class names do conflict, then the JVM will try to load them from the jar that comes earlier in the classpath. So Spring does not throw any exceptions and it simply autowires the class CustomerServiceImpl from the JAR loaded first (assuming CustomerServiceImpl implements CustomerService) .

Please have a look at here for more details on how class loading works.

Community
  • 1
  • 1
Vasu
  • 21,832
  • 11
  • 51
  • 67
  • I think classloading is something diffrent that DI from String. You should ge `UnsatisfiedDependencyException` if Spring cannot resolve which Bean to inject. – Krzysztof Atłasik Oct 31 '16 at 16:01