Skip to main content

Difference Between @Autowired and Constructor Injection (without @Autowired)

· 2 min read
Link Nuis
Java Developer

@Autowired Annotation

  • Purpose: Tells Spring to automatically inject a dependency into a field, setter, or constructor.
  • Usage:
MyService.java
@Component
public class MyService {
private final MyRepository repo;

@Autowired
public MyService(MyRepository repo) {
this.repo = repo;
}
}
  • Behavior:

    • Spring scans the context and finds a matching bean (MyRepository).
    • It injects that bean into the constructor automatically.
    • Useful when multiple constrctors exist (Spring needs to know which one to use).

Constructor Injection Without @Autowired

  • Since Spring 4.3: If a class has only one constructor, Spring will automatically use it for dependency injection without @Autowired.
  • Example:
MyService
@Component
public class MyService {
private final MyRepository repo;

public MyService(MyRepository repo) { // No @Autowired needed
this.repo = repo;
}
}
  • Behavior:
    • Spring sees there's only one constructor.
    • It assumes that's the one to use for injection.
    • Cleaner code, less boilerplate.

If MyService has more than one constructors, it'll throw compile time exception Class doesn't contain a matching constructor for autowiring:

MyService
@Component
class MyService {
private final MyRepository repo;

// We need set @Autowired here
public MyService(MyRepository repo) {
this.repo = repo;
}

// or here, but make sure OtherBean was existed
public MyService(MyRepository repo, OtherBean test) {
this.repo = repo;
}
}

To correct above example, we need to tell Spring, which constructor to use for injecttion by using @Autowired keyword:

MyService
@Component
class MyService {
private final MyRepository repo;

@Autowired
public MyService(MyRepository repo) { // Everything fine now
this.repo = repo;
}

public MyService(MyRepository repo, OtherBean test) {
this.repo = repo;
}
}

Comparation Table

Aspect@Autowired ConstructorConstructor Without @Autowired
Spring versionWorks in all versionsWorks automatically since Spring 4.3
Multiple constructorsNeeded to specify which oneMust use @Autowired to avoid ambiguity
ReadabilityExplicit, clear intentCleaner, less annotation noise
Best practiceUse when >1 constructorPrefer no @Autowired if only one constructor

So in short:

  • No @Autowired = works fine if there’s only one constructor (Spring auto-injects).
  • With @Autowired = explicit, necessary when multiple constructors exist.