栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

考虑在配置中定义类型为“ com.ensat.services.ProductService”的bean

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

考虑在配置中定义类型为“ com.ensat.services.ProductService”的bean

该bean不是由Spring创建的,因为

componentScan
attribute错过了所在的包
ProductServiceImpl

此外,

@EnableJpaRepositories
失踪。因此,Spring无法连接您的存储库。

@SpringBootApplication@ComponentScan(basePackages = {"hello","com.ensat.controllers"})@EntityScan("com.ensat.entities")

应替换为:

@SpringBootApplication@ComponentScan(basePackages = {"hello","com.ensat.controllers", "com.ensat.services";})@EntityScan("com.ensat.entities")@EnableJpaRepositories("com.ensat.repositories")

它将解决您的问题,但是这种方式克服了Spring和Spring Boot的配置优势。

如果

Application
bean类位于所有其他bean类所属的父包中或属于它的子包,则不再需要指定这两个注释:

@ComponentScan(basePackages = {"hello","com.ensat.controllers"})@EntityScan("com.ensat.entities")

@SpringBootApplication
课堂上。

例如,移入

Application
com.ensat
软件包并将所有Bean移入该软件包或其中一个子软件包都将解决您的配置问题并减轻您的配置。

package com.ensat;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Application extends SpringBootServletInitializer {    ...}

为什么呢

因为

@SpringBootApplication
包括已经(以及更多):

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@documented@Inherited@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan(excludeFilters = {        @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })public @interface SpringBootApplication {

但这使用当前类的包作为

basePackage
值来发现bean /实体/存储库等。

文档参考了这一点。

在这里:

许多Spring Boot开发人员的主类始终带有@ Configuration,@
EnableAutoConfiguration和@ComponentScan注释。由于这些注释经常一起使用(特别是如果您遵循上述最佳实践),因此Spring
Boot提供了一种方便的@SpringBootApplication替代方法。

@SpringBootApplication注释等效于使用@ Configuration,@
EnableAutoConfiguration和@ComponentScan及其默认属性

这里讨论了

@EnableAutoConfiguration
77.3 Use Spring Data Repository
point提供的关于实体发现的内容 :

Spring Boot会根据发现的@EnableAutoConfiguration尝试猜测@Repository定义的位置。
要获得更多控制权,请使用@EnableJpaRepositories批注(来自Spring Data JPA)。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/381556.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号