expected at least 1 bean which qualifies as autowire candidate

  • org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginController': Unsatisfied dependency expressed through field 'tokenService';

  • nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xx.common.security.service.TokenService' available: expected at least 1 bean which qualifies as autowire candidate.

  • 原因@SpringBootApplication只会扫描本包子包下的bean对象,由于TokenService和RedisService与鉴权部分路径不同,因为分别在common模块的两个子模块中(包名肯定不一样,虽然写成一样不会出现这样的问题,但是一般又不会写成一样)。所以扫描不到。

  • 解决方法

    • 在common子模块(需要在其他地方使用的工具类所在模块中)的resources下创建文件META-INF/spring.factories手动注入

      org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
        com.example.*(最好具体到类,下面注解同)
      
    • 或者在启动类上添加

      @SpringBootApplication(scanBasePackages={"com.example.*"})
      

    其他博客有看到会出现一些问题,还是建议在多模块中,那些工具类什么的,还是使用第一种解决方法。

    注意:启动类上加了@SpringBootApplication(basePackages = {})这个注解会导致controller扫描不到导致的,因为如果加了这个注解就不会扫描所在的包及子包的文件,需要将controller所在的包加入到注解@SpringBootApplication的大括号中

posted @ 2021-06-09 11:21  Codorld  阅读(3336)  评论(1编辑  收藏  举报