Two @Bean methods of one class register beans under the same name, so one definition replaces the other or startup fails
What it finds
A @Bean method registers a bean under its method name, or under the names given in @Bean("name"). Two @Bean methods of one class that end up with the same name define one bean twice: Spring either keeps one of the definitions, so the other method never runs and its object is missing where it was expected, or, as Spring Boot does by default, refuses to start because a definition would be overridden.
Reported is the second @Bean method of a class whose name, or one of whose given names, an earlier @Bean method of the class already uses. Methods with @Profile or a @Conditional... annotation are left alone, since those are often alternatives of which only one is active.
From the rule's source, duplicate_bean_name.rs.
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Profile; @Configurationclass Beans { @Bean Object client() { return new Object(); } @Bean("client")tx0 reports: a bean named client is already defined Object otherClient() { return new Object(); } @Bean(name = {"pool", "mainPool"}) Object pool() { return new Object(); } @Beantx0 reports: a bean named mainPool Object mainPool() { return new Object(); } @Bean @Profile("dev") Object dataSource() { return new Object(); } @Bean(name = "dataSource") @Profile("prod") Object productionDataSource() { return new Object(); }} Turn it on, off or suppress it
The rule runs from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/java:duplicate-bean-name" = "error"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/java:duplicate-bean-name] reason="..."tx0 explain tx0/java:duplicate-bean-name shows the same in the terminal. Found a false positive? Report it.