Kumar Gaurav
Kumar Gaurav

Reputation: 1327

why do we need componentScan in spring

This question might be trivial but still i'm unable to find a good reason or best practice towards @ComponentScan in Spring

DI works just by self annotating the class then why do we need @ComponentScan

What is the best practice towards this?

Upvotes: 0

Views: 4968

Answers (1)

Arvind Katte
Arvind Katte

Reputation: 1003

@ComponentScan tells Spring in which packages you have annotated classes which should be managed by Spring.

Spring needs to know which packages contain spring beans, otherwise you would have to register each bean individually in(xml file). This is the use of @ComponentScan.

Take a simple example, you have a class and annotated with @Controller in a package package com.abc.xyz; , you have to tell the spring to scan this package for Controller class, if spring didn't scan this package, then spring will not identifies it as a controller class.

Suppose if your dealing with configuration file,

<context:component-scan base-package="com.abc.xyz"> like this,

When spring loads the xml file, this tag will search the all the classes present in the package com.abc.xyz, so any of the class containing @controller, @Repository @Service etc.., if it found then spring will register these annotated class in the bean factory.

Suppose if your using spring boot application,

Then your spring-boot application is annotated with The@SpringBootApplication.

@SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes.

One more point if you didn;t specify the base package name in @ComponentScan,
it will scan from the package, where the @Springbootapplication present

Upvotes: 4

Related Questions