Why EntityScan , EnableJpaRepositories annotations required if we are already using componentScan annotation?

huangapple go评论64阅读模式
英文:

Why EntityScan , EnableJpaRepositories annotations required if we are already using componentScan annotation?

问题

我已经在Spring Boot应用的Main类中使用了ComponentScan注解,但如果我只使用这个注解,那在获取存储库引用时会出现问题。因此,为了解决这个问题,我正在使用EntityScanEnableJpaRepositories这两个注解与ComponentScan一起使用。

@EntityScan(basePackages={"com.gonkar.fleetms.models"})
@EnableJpaRepositories(basePackages={"com.gonkar.fleetms.repositories"})

所以我的问题是,为什么需要使用另外两个注解?如果我已经在使用@ComponentScan了。

英文:

I am already using ComponentScan annotation in Main class of Spring Boot app , but If I use only this annotation it will gives issue while getting repositories reference. So to overcome this I am using EntityScan and EnableJpaRepositories annotations with componentScan.

@EntityScan(basePackages={"com.gonkar.fleetms.models"})
@EnableJpaRepositories(basePackages={"com.gonkar.fleetms.repositories"})

So my question is why its required to use other two annotations? if I am already using @ComponentScan.

答案1

得分: 12

@ComponentScan注解用于为被标注为@Component@Controller / @RestController@Service@Repository的类创建Bean。它将它们标记为要添加到Spring容器中(使它们有资格进行依赖注入并允许它们被@Autowired)。

@EntityScan注解不会创建任何Bean,它标识哪些类应该被JPA持久化上下文使用。

@EnableJpaRepositories注解用于从Spring Data接口创建存储库类。

这三个注解经常一起使用,但它们负责不同的事情。

英文:

The @ComponentScan annotation is used to create beans for classes annotated with @Component, @Controller / @RestController, @Service, @Repository. It marks them for being added to the Spring container (making them eligible for dependency injection and allowing them to be @Autowired).

The @EntityScan annotation doesn't create any beans, it identifies which classes should be used by a JPA persistence context.

The @EnableJpaRepositories annotation is used to create repository classes from Spring Data interfaces.

All three annotation are often used together, but they are responsible for different things.

huangapple
  • 本文由 发表于 2020年10月5日 12:31:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64202520.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定