VB_
VB_

Reputation: 45682

@Autowired & Spring context hierarchy

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..

Upvotes: 2

Views: 1566

Answers (3)

Prasad
Prasad

Reputation: 3795

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.

Upvotes: 3

Aniket Thakur
Aniket Thakur

Reputation: 68905

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.

Upvotes: 0

makasprzak
makasprzak

Reputation: 5220

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

Upvotes: 0

Related Questions