Search code examples
javaspringannotationsspring-annotations

Why @Component is used in Controller annotation


Below is source code of For Component Interface

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Component {

and for Spring Controller annotation is as below

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {

Why @Component is added in Controller annotation ? What is its purpose ? What if I remove this line ?

I am clear about below annotation types which are used to create custom annotations.

@Documented Whether to put the annotation in Javadocs
@Retention  When the annotation is needed
@Target     Places the annotation can go    
@Inherited  Whether subclasses get the annotation

Solution

  • @Controller is a @Component (just like @Service, @Repository, @Endpoint etc.).

    The @Component is used as a meta-annotation here so that it can be picked-up using component-scanning. Next to that the @Controller is a special component which will have some added functionality (Spring MVC takes care of that). If you remove the @Component annotation component-scan will not be able to detect it anymore.

    You can also create your own @Component based annotations by simply creating your own annotation and putting @Component on it.