Difference between @EntityScan and @ComponentScan

大城市里の小女人 提交于 2019-11-26 22:44:43

问题


I am trying to understand the difference here. I see that a class has been annotated with both of them with same package example :

@Configuration
@EntityScan("some.known.persistence")
@ComponentScan({ "some.known.persistence"})
public class ApiConfig {

}

I understand the differences from API docs but want to understand in detail. Also does it mean that anything that is scanned by @ComponentScan is having wider visibility wrt Spring context and @EntityScan does not. If so using some attribute with @ComponentScan should have sufficed the need to bind in a JPA context, isn't it?


回答1:


The @ComponentScan annotation is used to automatically create beans for every class annotated with @Component, @Service, @Controller, @RestController, @Repository, ... and adds them to the Spring container (allowing them to be @Autowired).

The @EntityScan on the other hand does not create beans as far as I know. It only identifies which classes should be used by a specific persistence context. Since Spring boot 1.4 that includes JPA, MongoDB, neo4j, Cassandra and CouchBase.

Why they're not merged? Well, I'm not on the Spring team, but since they have different meanings, why should they be merged? The @EntityScan should mainly be used to scan your entity packages, while the @ComponentScan should scan all packages that contain Spring beans, so the following is very likely:

@ComponentScan("org.example.base")
@EntityScan("org.example.base.entities")
public class MyConfig {

}


来源:https://stackoverflow.com/questions/38896414/difference-between-entityscan-and-componentscan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!