InterviewSolution
| 1. |
When should you use @Component vs @Bean annotations? |
|
Answer» @Bean is used when we WANT to define a class method as a Spring bean producer. It is used in conjunction with a configuration class (annotated with @Configuration). Here we explicitly declare the Spring beans. On the other hand, @Component is used in classes, marking it as a source of bean definitions. However, it only works when we enable component scan in the application and the given class is included in it. So, in this case, we let Spring pick up the bean. Now the end-result for both annotations is the same as Spring will add the beans the context. However, there are some minor characteristics that can be considered while choosing between @Bean and @Component. Let us CONSIDER a scenario where we have a module containing few utility services, that are being shared across multiple applications. Though these services provide nice features, not all of them are needed by each application. Here, if mark these utility service classes as @Component and set them for component scan in the application, we might end up detecting more beans than necessary. In this case, we either have to adjust the filtering of the component scan or provide configurations where even the unused beans can run. In this scenario, it would be BETTER to use @Bean annotation and only instantiate the beans, that are REQUIRED INDIVIDUALLY in each application. In a nutshell, we should use @Bean for adding third-party classes to the context, whereas @Component when it is inside the same application. |
|