@ComponentScan is used for scanning all your components those are marked as @Controller, @Service, @Repository, @Component etc… where @EntityScan is used to scan all your Entities those are marked @Entity for any configured JPA in your application.
@ComponentScan:
@Retention(value=RUNTIME)
@Target(value=TYPE)
@Documented
@Repeatable(value=ComponentScans.class)
public @interface ComponentScan
Configures component scanning directives for use with @Configuration
classes. It is as same as writing Spring XML’s <context:component-scan>
element. The value()
attribute may be specified to define specific packages to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation. i.e
@ComponentScan("org.example.base")
public class MyConfig {
...
}
Point to be noted here is that then you use XML’s <context:component-scan>
it comes with an attribute annotation-config
. Which is boolean flag “Indicates whether the implicit annotation post-processors should be enabled. Default is ‘true’.” In simple words, if it is true then you can create objects of you classes and resolve dependencies by annotating them with @Controller, @Service, @Repository etc and if you set it as false then you will have to declare all your Spring Beans into XMLs.
But when using @ComponentScan
, in almost all cases default annotation config processing (e.g. processing @Autowired
and friends) is assumed. Furthermore, when using AnnotationConfigApplicationContext
, annotation config processors are always registered, meaning that any attempt to disable them at the @ComponentScan
level would be ignored.
@EntityScan
It configures the base packages used by auto-configuration when scanning for entity classes.
Using @EntityScan
will cause auto-configuration to:
- Set the
packages scanned
for JPA entities. - Set the packages used with
SessionFactory
. - Set the
initial entity set
used with Spring DataMongoDB
,Cassandra
andCouchbase
mapping contexts.
Hope this clear your doubts!!