2

Suppose I've got application contexts hierarchy: A (parent), B (extends A), C (extends A). Suppose now I write something like @Autowired private MyBean myBean

Question: WHERE Spring will look for myBean? In other words in WHICH CONTEXT it'll look? Suppose bean is present in all 3 contexts..

VB_
  • 45,112
  • 42
  • 145
  • 293

3 Answers3

3

It depends on from which context your MyBean is being referenced.

See the below scenarios:

Lets assume MyBean is being referenced in bean ReferencingBean.

Scenario 1: If ReferencingBean is in context A, autowire will get MyBean from context A.

Scenario 2: If ReferencingBean is in context B, autowire will get MyBean from context B.

Scenario 3: If ReferencingBean is in context C, autowire will get MyBean from context C.

Child contexts beans cannot be cross referenced. Meaning, if ReferencingBean is in context B, it has no visibility into context C and vice versa.

Prasad
  • 3,785
  • 2
  • 14
  • 23
  • I would add, that if ReferencingBean is in context A or B, but MyBean is defined in C, then autowire will get MyBean from context C. Child contexts have references to parent context beans. – Vadim Kirilchuk Sep 25 '15 at 07:52
0

The @Autowired annotation is auto wire the bean by matching data type.

So in your case it will look for a bean of type MyBean.

It will always look in the current application context first. When a given ApplicationContext cannot resolve a bean, it will pass on the resolution request to its parent. So it will start from application context where you have @Autowired private MyBean myBean.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • the question is WHERE it will look? In other words in WHICH CONTEXT? Suppose that bean is present in all 3 contexts... – VB_ Jul 02 '14 at 10:58
  • what do you mean by current application context? We have situation with two siblings. I mean both `B` and `C` extends `A`. Which of them will be current? – VB_ Jul 02 '14 at 11:20
0

In both. If the bean is defined twice, first in A then in B, the B will override A. See also this answer https://stackoverflow.com/a/4250093/1937263

Community
  • 1
  • 1
makasprzak
  • 5,082
  • 3
  • 30
  • 49