Spring Annotations
Learn about a few interview questions regarding Spring annotations.
We'll cover the following...
- What is the purpose of the @Component annotation?
- What is the difference between @Component, @Service, @Repository, and @Controller?
- Why is @Primary annotation used?
- Why is @Qualifier annotation used?
- Which annotations takes precedence: @Primary or @Qualifier?
- Why is the @Required annotation used?
- What is the purpose of @Autowired annotation?
- Both @Bean and @Component annotations create beans. What is the difference between the two?
- What is the difference between @Inject and @Autowired in Spring? Which one to use under which condition?
What is the purpose of the @Component
annotation?
@Component
annotation is used to define a bean. This annotation is placed on a Java class. The XML file contains the <context: component-scan>
tag to enable component scanning. Spring container scans the package (and its sub-packages) specified in the component-scan
tag. It will register all classes marked with the @Component
annotation as beans.
Using the @Component
annotation can save a lot of time spent in writing lengthy bean definition code in XML.
What is the difference between @Component
, @Service
, @Repository
, and @Controller
?
A typical application is divided into layers. The @Component
annotation is generic and denotes any Spring-managed bean. It can be used in any layer of the application, whereas the other three are specific to layers. @Controller
is used in the web layer, @Service
is used on ...