Issue
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.
Which of these beans will be actually used as by default Spring is singleton?
What happens when I remove @Component?
Solution
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.
Answered By - Maksym Rudenko
Answer Checked By - Pedro (JavaFixing Volunteer)