2

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?

rsp
  • 813
  • 2
  • 14
  • 26
  • 2
    I recommend you to try your hands on Spring. To check such a scenario yourself, you will need only 1 file and 90% of code you already have written in the question ;) – Maksym Rudenko May 25 '20 at 08:46

1 Answers1

1

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.

Maksym Rudenko
  • 706
  • 5
  • 16
  • I tried to look for any official documentation for this or some reference, but could not find. Can you provide some link if possible? – rsp May 25 '20 at 08:46
  • 1
    [link](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/NoUniqueBeanDefinitionException.html) and here is a good [article](https://springframework.guru/fixing-nonuniquebeandefinitionexception-exceptions/) – Maksym Rudenko May 25 '20 at 08:47