Question

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
Was it helpful?

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.

OTHER TIPS

@Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.

Read this answer

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top