Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Two @Bean methods with the same bean name should consistently throw an exception #33330

Closed
LuckyCurve opened this issue Aug 6, 2024 · 2 comments
Assignees
Labels
in: core Issues in core modules (aop, beans, core, context, expression) type: enhancement A general enhancement
Milestone

Comments

@LuckyCurve
Copy link

Affects: spring version: 6.1.11, spring-boot version: 3.3.2


It confuses me that when I use the @Bean method to register two beans with the same name into the container and start the Spring application context, it succeeds. However, if I use @Component to register two beans with the same name into the container and start the context, it throws an exception. Why does this happen, and how should I understand it?

example1: the method named beanA will execute and beanB will be ignored, start Spring application context will succeed. It seems always execute above method

@SpringBootApplication
public class LuckySpringBootStarterApplication {

    @Bean(name = "a")
    public String beanA() {
        return "a";
    }

    @Bean(name = "a")
    public String beanB() {
        return "b";
    }

    public static void main(String[] args) {
        SpringApplication.run(LuckySpringBootStarterApplication.class, args);
    }
}

example2 will throw an exception

@SpringBootApplication
public class LuckySpringBootStarterApplication {

    @Component("a")
    static class A {

    }

    @Component("a")
    static class B {

    }

    public static void main(String[] args) {
        SpringApplication.run(LuckySpringBootStarterApplication.class, args);
    }
}
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [space.luckycurve.LuckySpringBootStarterApplication]
	at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:179) ~[spring-context-6.1.11.jar:6.1.11]
	at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:417) ~[spring-context-6.1.11.jar:6.1.11]
	at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:290) ~[spring-context-6.1.11.jar:6.1.11]
	at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:349) ~[spring-context-6.1.11.jar:6.1.11]
	at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:118) ~[spring-context-6.1.11.jar:6.1.11]
	at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:789) ~[spring-context-6.1.11.jar:6.1.11]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:607) ~[spring-context-6.1.11.jar:6.1.11]
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.3.2.jar:3.3.2]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-3.3.2.jar:3.3.2]
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:456) ~[spring-boot-3.3.2.jar:3.3.2]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:335) ~[spring-boot-3.3.2.jar:3.3.2]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1363) ~[spring-boot-3.3.2.jar:3.3.2]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1352) ~[spring-boot-3.3.2.jar:3.3.2]
	at space.luckycurve.LuckySpringBootStarterApplication.main(LuckySpringBootStarterApplication.java:21) ~[classes/:na]
	at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) ~[na:na]
	at java.base/java.lang.reflect.Method.invoke(Method.java:580) ~[na:na]
	at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:50) ~[spring-boot-devtools-3.3.2.jar:3.3.2]
Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'a' for bean class [space.luckycurve.LuckySpringBootStarterApplication$B] conflicts with existing, non-compatible bean definition of same name and class [space.luckycurve.LuckySpringBootStarterApplication$A]
	at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.checkCandidate(ClassPathBeanDefinitionScanner.java:361) ~[spring-context-6.1.11.jar:6.1.11]
	at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:288) ~[spring-context-6.1.11.jar:6.1.11]
	at org.springframework.context.annotation.ComponentScanAnnotationParser.parse(ComponentScanAnnotationParser.java:128) ~[spring-context-6.1.11.jar:6.1.11]
	at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:306) ~[spring-context-6.1.11.jar:6.1.11]
	at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:246) ~[spring-context-6.1.11.jar:6.1.11]
	at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:197) ~[spring-context-6.1.11.jar:6.1.11]
	at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:165) ~[spring-context-6.1.11.jar:6.1.11]
	... 16 common frames omitted
@spring-projects-issues spring-projects-issues added the status: waiting-for-triage An issue we've not yet triaged or decided on label Aug 6, 2024
@sbrannen sbrannen added the in: core Issues in core modules (aop, beans, core, context, expression) label Aug 6, 2024
@jhoeller jhoeller self-assigned this Aug 6, 2024
@jhoeller
Copy link
Contributor

jhoeller commented Aug 6, 2024

The problem is specific to @Bean methods on the same @Configuration class where multiple methods for the same bean name are treated as overloaded factory methods for the same bean. In that sense, this is related to #22609 where we tried to turn off such overloading by default. However, the specific scenario suggested above still slips through there since it uses the same bean name for two distinct method names (none of which matches the bean name).

@jhoeller jhoeller changed the title Two beans with duplicate names should throw an exception? Two @Bean methods with the same bean name should consistently throw an exception Aug 6, 2024
@jhoeller jhoeller added type: enhancement A general enhancement and removed status: waiting-for-triage An issue we've not yet triaged or decided on labels Aug 6, 2024
@jhoeller jhoeller added this to the 6.2.0-M7 milestone Aug 6, 2024
@LuckyCurve
Copy link
Author

LuckyCurve commented Aug 7, 2024

The problem is specific to @Bean methods on the same @Configuration class where multiple methods for the same bean name are treated as overloaded factory methods for the same bean. In that sense, this is related to #22609 where we tried to turn off such overloading by default. However, the specific scenario suggested above still slips through there since it uses the same bean name for two distinct method names (none of which matches the bean name).

@jhoeller Could you show me some documentation related to overloaded factory methods? I would like to understand the details.

The example before simplification is as follows. I want to provide an auto configuration class that can decide whether to decorate RestTemplate with @LoadBalanced annotation or not, and in other place, I can get the RestTemplate with same name.

   @Bean(name = "restTemplate")
   @ConditionalOnMissingBean(name = "restTemplate")
   public RestTemplate defaultRestTemplate() {
       return new RestTemplate();
   }

   @Bean(name = "restTemplate")
   @Profile("dev")
   public RestTemplate devRestTemplate() {
       return new RestTemplate();
   }

   @Bean(name = "restTemplate")
   @Profile("test")
   @LoadBalanced
   public RestTemplate testRestTemplate() {
       return new RestTemplate();
   }

The code aims to achieve a similar effect to: if (some condition) return common RestTemplate - else if (others condition) return enhanced RestTemplate - else return default RestTemplate. However, I failed, I temporarily solved the problem by moving the defaultRestTemplate method to the bottom of the list, how can I handle this more gracefully?

Best regards

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
in: core Issues in core modules (aop, beans, core, context, expression) type: enhancement A general enhancement
Projects
None yet
Development

No branches or pull requests

4 participants