Spring Annotations

Learn about a few interview questions regarding Spring annotations.

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 ...