Avoid by-name constructor injection without @Qualifier
ID |
java.spring_avoid_byname_constructor_injection |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
best-practice, reliability, spring |
Description
Reports @Autowired constructors that have multiple parameters of the same type without @Qualifier annotations. Spring resolves such ambiguity by matching parameter names to bean names, which is fragile.
Rationale
When a constructor has two or more parameters of the same type and no @Qualifier, Spring falls back to matching the parameter name against registered bean names. This by-name resolution breaks silently when parameter names are refactored, obfuscated, or compiled without debug info (-parameters flag absent).
// Bad - relies on parameter names for disambiguation
@Autowired
public MyService(DataSource primary, DataSource secondary) { ... }
Remediation
Add @Qualifier to each parameter to make the binding explicit and refactor-safe.
// Good - explicit qualifier
@Autowired
public MyService(
@Qualifier("primary") DataSource primary,
@Qualifier("secondary") DataSource secondary) { ... }