skip to content

@Autowired Resolution

How @Autowired resolves a dependency by type, what required=false changes, and which exception you get when there are zero or several candidates. A staple question, because those two exceptions are ones you will genuinely debug.

part ofSpring Frameworkoverview, primer and where to startread it →
on this pageshow

questions

5

What does @Autowired do, and what does it mean that Spring resolves it "by type"?

level: juniorimportance: must knowfreq 90%

answer

  1. inject by declared type
  2. interface param -> impl bean
  3. constructor > setter > field
  4. single constructor = annotation optional (4.3+)
  5. one candidate needed

basics

~10 s

@Autowired tells Spring to inject a dependency automatically. "By type" means Spring looks in its container for a bean whose type matches the field, constructor parameter, or setter parameter, and wires that bean in.

solid answer

~40 s

@Autowired marks an injection point — a constructor, setter, or field — that the Spring container should fill from its own beans. Resolution is primarily by type: Spring finds a bean assignable to the required type and injects it. It works with the declared type, so an interface parameter matches whichever bean implements it. Constructor injection is preferred (and since Spring 4.3 a single constructor is autowired without the annotation). If exactly one candidate matches, injection succeeds. Zero matching candidates or more than one both cause problems — a missing required bean fails startup, and multiple candidates are ambiguous unless narrowed. @Autowired is handled by an infrastructure bean post-processor, not by reflection you write yourself, so it happens automatically during bean creation.

code

java · 17 lines
java
public interface GreetingService { String greet(String name); }

@Service
class EnglishGreetingService implements GreetingService {
    public String greet(String name) { return "Hello, " + name; }
}

@Service
class Welcomer {
    private final GreetingService greetingService;

    // Single constructor -> @Autowired optional since Spring 4.3.
    // Resolved by type: the one GreetingService bean is injected.
    Welcomer(GreetingService greetingService) {
        this.greetingService = greetingService;
    }
}

go deeper

for a junior

Know it injects a matching bean by type and prefer constructor injection.

for a middle

Explain the single-constructor 4.3 rule and interface-to-impl matching.

for a senior

Tie 'by type' to the container search and name the two failure exceptions.

for a principal

Frame @Autowired as declarative wiring handled by an infrastructure post-processor and reason about type/generics matching.

### What @Autowired is `@Autowired` (package `org.springframework.beans.factory.annotation`) marks an **injection point** where the Spring IoC container should supply a collaborating bean. You can put it on a **constructor**, a **setter (or any method)**, or a **field**. It is Spring's own annotation (distinct from JSR-330 `@Inject`, covered by a sibling topic). ### "By type" resolution When Spring creates a bean, for each `@Autowired` point it takes the **declared type** of the target (field type / parameter type) and searches the `ApplicationContext` for a bean **assignable** to that type. Because it matches by type, you normally autowire an **interface** and Spring injects whatever concrete bean implements it: ```java @Autowired PaymentGateway gateway; // matches the single PaymentGateway bean ``` If the container holds exactly one bean of that type, it is injected. Generics are respected too: `@Autowired Repository<Order>` will not match `Repository<Customer>`. ### Constructor vs setter vs field - **Constructor injection** is recommended: dependencies are final, the object is fully initialized, and it is testable without Spring. Since **Spring 4.3**, if a class has a **single constructor**, `@Autowired` is optional there. - **Setter / method injection** allows optional or reconfigurable dependencies. - **Field injection** is concise but discouraged (hard to test, hides required deps). ### Who performs it You don't call anything. The infrastructure bean `AutowiredAnnotationBeanPostProcessor` scans each bean during creation and fills the injection points. It is registered automatically by `<context:annotation-config>`, component scanning, or a Spring Boot auto-config. ### The two failure modes - **No candidate**: a required `@Autowired` with zero matching beans fails **at startup** with `NoSuchBeanDefinitionException`. - **Multiple candidates**: two+ beans of the type are **ambiguous**; without a tie-breaker Spring throws `NoUniqueBeanDefinitionException`. ### When to use Use `@Autowired` (via constructor) for required collaborators between your own beans. It keeps wiring declarative rather than manual `new`.

  • Where can you put @Autowired?
    On a constructor, on a setter or any config method, or directly on a field. Constructor injection is preferred; field injection is discouraged because it hides dependencies and hampers testing.
  • Do you still need @Autowired on a constructor?
    Not if the class has exactly one constructor — since Spring 4.3 Spring autowires the sole constructor implicitly. With multiple constructors you must annotate one to pick it.

saying these in an interview costs you the question

  • Thinking @Autowired matches by field/bean name first rather than by type
  • Believing you must always write @Autowired on every constructor
  • Claiming @Autowired works via your own reflection code rather than a bean post-processor

context

open as a page

What does required=true vs required=false on @Autowired mean, and how else can you model an optional dependency?

level: middleimportance: must knowfreq 75%

basics

~20 s

required=true (the default) means the bean must exist or startup fails. required=false means Spring skips injection and leaves the field null if no matching bean is found. You can also declare the dependency as Optional<T> or use @Nullable.

open as a page

Walk through the resolution order Spring uses for a single-valued @Autowired point, and when NoSuchBeanDefinitionException vs NoUniqueBeanDefinitionException is thrown.

level: seniorimportance: must knowfreq 70%

basics

~20 s

Spring first collects all beans assignable to the required type. Zero candidates and required -> NoSuchBeanDefinitionException. One candidate -> inject it. Many candidates -> narrow by @Primary, then @Qualifier, then by matching the field/parameter name; if still not unique -> NoUniqueBeanDefinitionException.

open as a page

Which component processes @Autowired, and at what point in the bean lifecycle does constructor vs field/setter injection happen?

level: seniorimportance: should knowfreq 55%

basics

~10 s

AutowiredAnnotationBeanPostProcessor handles @Autowired (and @Value and @Inject). Constructor injection is resolved when the bean is instantiated; field and setter injection happen afterward during the property-population phase, before initialization callbacks.

open as a page

What happens when @Value is placed on an injection point (or alongside @Autowired), and how does that interact with by-type autowiring?

level: principalimportance: should knowfreq 40%

basics

~20 s

@Value tells Spring to inject a resolved value (from a property or expression) instead of looking up a bean by type. It's handled by the same processor as @Autowired, and when @Value supplies a value that value wins — no by-type bean lookup occurs for that point.

open as a page