@EntityScan和@ComponentScan之间的区别 [英] Difference between @EntityScan and @ComponentScan

查看:1524
本文介绍了@EntityScan和@ComponentScan之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解此处的区别.我看到一个类都使用相同的包示例进行了注释:

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 {

}

我了解与API文档的区别,但希望详细了解.这是否也意味着通过@ComponentScan扫描的所有内容在Spring上下文中都具有更广泛的可见性,而@EntityScan没有.如果是这样,将某些属性与@ComponentScan一起使用就足以满足在JPA上下文中进行绑定的需求,不是吗?

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?

推荐答案

@ComponentScan注释用于为每个用@Component@Service@Controller@RestController@Repository,...,并将它们添加到Spring容器中(允许它们成为@Autowired).

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).

另一方面,据我所知,@EntityScan不会创建bean.它仅标识特定持久性上下文应使用哪些类.从Spring Boot 1.4开始,其中包括JPA,MongoDB,neo4j,Cassandra和CouchBase.

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.

为什么它们没有合并?好吧,我不在Spring团队中,但是由于它们的含义不同,为什么要将它们合并? @EntityScan应该主要用于扫描您的实体程序包,而@ComponentScan应该扫描所有包含Spring bean的程序包,因此很可能出现以下情况:

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 {

}

这篇关于@EntityScan和@ComponentScan之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆