Duplicate Bean Name In Configuration Class
ID |
java.spring_bean_names_unique |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
best-practice, reliability, spring |
Description
Reports @Bean methods within the same @Configuration class whose bean name collides with an earlier @Bean method’s name.
A pair is not reported when either method carries a @Conditional… or @Profile annotation. Declaring one bean name twice under mutually exclusive conditions is the standard Spring idiom for a conditionally-typed bean — exactly one definition is ever registered, so neither overrides the other. The conditions themselves are not evaluated, so two gates that can both hold carry the same name past this rule.
Rationale
The bean name is either given explicitly (@Bean(name = "…"), @Bean(value = "…"), @Bean("…")) or defaults to the method name. When two @Bean methods in one @Configuration class resolve to the same name, one bean definition silently overrides the other in the application context. The bean wired at runtime is then not the one a reader would expect from the source, and the mistake is invisible until the wrong implementation is injected somewhere.
// Bad - both methods resolve to bean name "auditService"
@Configuration
class AuditConfig {
@Bean
public AuditService auditService() {
return new DefaultAuditService();
}
@Bean("auditService")
public AuditService fileAuditService(AuditProperties props) {
return new FileAuditService(props);
}
}
Remediation
Give each @Bean method in the class a distinct, meaningful name.
// Good - distinct names
@Configuration
class AuditConfig {
@Bean
public AuditService auditService() {
return new DefaultAuditService();
}
@Bean("fileAuditService")
public AuditService fileAuditService(AuditProperties props) {
return new FileAuditService(props);
}
}