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

查看:37
本文介绍了@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 扫描的任何内容都具有更广泛的可见性,而 @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 注释的类自动创建 bean,@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天全站免登陆