Difference Between @Autowired and Constructor Injection (without @Autowired)
· 2 min read
@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).
- Spring scans the context and finds a matching bean (
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 Constructor | Constructor Without @Autowired |
|---|---|---|
| Spring version | Works in all versions | Works automatically since Spring 4.3 |
| Multiple constructors | Needed to specify which one | Must use @Autowired to avoid ambiguity |
| Readability | Explicit, clear intent | Cleaner, less annotation noise |
| Best practice | Use when >1 constructor | Prefer 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.
