Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is given priority in below scenario @Bean or @Component?

I am learning concepts of Spring & I came across @Bean & @Component annotations. I want to know what will happen in below scenario:

@Configuration
class ConfigClass {

  @Bean
  public ComponentClass ComponentClass() {
    return new ComponentClass(someDependency1, someDependency2, someDependency3);
  }
}

@Component
class ComponentClass{
  private SomeDependency1 sd1;
  private SomeDependency2 sd2;
  private SomeDependency3 sd3;

  public ComponentClass(SomeDependency1 sd1, SomeDependency2 sd2, SomeDependency3 sd3) {
    /* initialize here */
  }
}

I have declared ComponentClass as @Component which means it is a spring bean now. But I have also defined a @Bean for it in config class separately.

  1. Which of these beans will be actually used as by default Spring is singleton?

  2. What happens when I remove @Component?

like image 325
rsp Avatar asked Dec 01 '25 10:12

rsp


1 Answers

Spring will notice a mistake and throw NoUniqueBeanDefinitionException during application startup. If you remove @Component annotation it will work as expected, @Bean will be used for initialization.

like image 159
Maksym Rudenko Avatar answered Dec 04 '25 00:12

Maksym Rudenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!