spring boot自动注入出现Consider defining a bean of type 'xxx' in your configuration问题
搭建完spring boot的demo后自然要实现自动注入来体现spring ioc的便利了,但是我在实施过程中出现了这么一个问题,见下面,这里找到解决办法记录下来,供遇到同样的问题的同僚参考Description:Field userRepository in com.addresslist.controller.UserController required a bean of type...
搭建完spring boot的demo后自然要实现自动注入来体现spring ioc的便利了,但是我在实施过程中出现了这么一个问题,见下面,这里找到解决办法记录下来,供遇到同样的问题的同僚参考
Description:
Field userRepository in com.addresslist.controller.UserController required a bean of type 'com.addresslist.repository.UserRepository' that could not be found.
Action:
Consider defining a bean of type 'com.addresslist.repository.UserRepository' in your configuration.
根据英文的提示是在配置中找不到一个指定自动注入类型的bean,经过多方排查得出结论:
正常情况下加上@Component注解的类会自动被Spring扫描到生成Bean注册到spring容器中,既然他说没找到,也就是该注解被没有被spring识别,问题的核心关键就在application类的注解@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 {
这个注解其实相当于下面这一堆注解的效果,其中一个注解就是@Component,**在默认情况下只能扫描与控制器在同一个包下以及其子包下的@Component注解,以及能将指定注解的类自动注册为Bean的@Service @Controller和@Repository,**至此明白问题所在,之前我将接口与对应实现类放在了与控制器所在包的同一级目录下,这样的注解自然是无法被识别的。
至此,得出两种解决办法:
1 .将接口与对应的实现类放在与application启动类的同一个目录或者他的子目录下,这样注解可以被扫描到,这是最省事的办法。
2 .在指定的application类上加上这么一行注解,手动指定application类要扫描哪些包下的注解。
@ComponentScan(basePackages = {"com.addresslist.repository","com.addresslist.xxx"})
public class AddresslistApplication {
相关问题:
【springboot使用jpa启动报错consider defining a bean of type ‘..**Repository’ in your configuration.】
参考文献
CSDN博主「梦岚如雪」的博客:https://blog.csdn.net/a532672728/article/details/77702772/
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)