SpringBoot包路经扫描问题导致的NoSuchBeanDefinitionException: No qualifying bean of type

wylc123 1年前 ⋅ 1813 阅读

一种原因:

其实导致这个异常的原因很简单,就是因为Springboot未能正常将其扫描并没注入到容器中。而且一般在使用Springboot的初始框架中,启动类位置于所有Service,Entity,Controller或者其它类的最上层的话,这个问题很少会出现。

解决方案:

方案一、把 @SpringBootApplication 注解的 SpringBoot 入口类移到上层 root 包中,使 JpaRepository 子接口位于 root 包及其子包中。

方案二、在 SpringBoot 入口类上添加

(1) @ComponentScan(basePackages = "xxx.xxx.xxx"):扫描 @Controller、@Service 注解;
(2) @EnableJpaRepositories(basePackages = "xxx.xxx.xxx"):扫描 @Repository 注解;
(3) @EntityScan(basePackages = "xxx.xxx.xxx"):扫描 @Entity 注解;

第二种原因:(比一种的设置的路径要优先,当用第一中方法不起作用时,可能时这种情况)

Spring Boot + MyBatis No qualifying bean of type

在做SpringMVC+MyBatis结合的项目的时候,也出过这种诡异的事情。问题出在我的项目目录结构有问题,

或者说我的MybatisConfig文件的扫描注解路径有问题。包结构看上面... MyBatisConfig代码如下:

@Configuration
@MapperScan("com.jy.affairs.mapper.*")
public class MybatisConfig {
 
 
    @Autowired
    private Environment environment;
    private RelaxedPropertyResolver propertyResolver;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private MybatisProperties properties;
    @Autowired
    private ResourceLoader resourceLoader = new DefaultResourceLoader();
    @Autowired(required = false)
    private Interceptor[] interceptors;
    @Autowired(required = false)

注解的路径是:

@MapperScan("com.jy.affairs.mapper.*")
MyBatis的Mapper扫描路径是指的包名,* 不代表类,代表的是包,而项目中的Mapper类都在com.jy.affairs.mapper包下面,并没有再向下的层级,所以Mybatis没有扫描到Mapper类,就报了刚才的错误。

其他Spring NoSuchBeanDefinitionException原因分析

更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: