Spring Boot自动扫描
进行 Spring Boot 和 Mybatis 进行整合的时候,Spring Boot 注解扫描的时候无法扫描到 Application 类的以外的包下面的注解,如下图:
App 就是 Application 类,下图是 ProductMapper 类:
@Mapper public interface ProductMapper {@Insert(</span>"insert into products (pname,type,price)values(#{pname},#{type},#{price}"<span style="color: rgba(0, 0, 0, 1)">) </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> add(Product product); @Delete(</span>"delete from products where id=#{arg1}"<span style="color: rgba(0, 0, 0, 1)">) </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span> deleteById(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> id); @Update(</span>"update products set pname=#{pname},type=#{type},price=#{price} where id=#{id}"<span style="color: rgba(0, 0, 0, 1)">) </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> update(Product product); @Select(</span>"select * from products where id=#[arg1}"<span style="color: rgba(0, 0, 0, 1)">) </span><span style="color: rgba(0, 0, 255, 1)">public</span> Product getById(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> id); @Select(</span>"select * from productsorder by id desc"<span style="color: rgba(0, 0, 0, 1)">) </span><span style="color: rgba(0, 0, 255, 1)">public</span> List<Product><span style="color: rgba(0, 0, 0, 1)"> queryByLists();
}
App 类运行的时候后台就会报没有找到 ProductMapper 这个类 bean:
1 2 3 4 5 | Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException:< br > No qualifying bean of type 'com.self.spring.mapper.ProductMapper' available at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:353) at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:340) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1090) at com.self.spring.springboot.App.main(App.java:17) |
造成上面的错误原因:SpringBoot 项目的 Bean 装配默认规则是根据 Application 类所在的包位置从上往下扫描! “Application 类”是指 SpringBoot 项目入口类。这个类的位置很关键:
如果 Application 类所在的包为:io.github.gefangshuai.app
,则只会扫描io.github.gefangshuai.app
包及其所有子包,如果 service 或 dao 所在包不在io.github.gefangshuai.app
及其子包下,则不会被扫描!
解决方法
第一种:Application 类放在父包下面,所有有注解的类放在同一个下面或者其子包下面
第二种:指定要进行扫描注解的包 URL,上面的问题的解决方案可以在 Application 类上面加注解扫描 mapper 接口包下面的类。
@SpringBootApplication @MapperScan(basePackages="com.self.spring.springboot.mapper") public class App { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(App.class, args); System.out.println(context.getBean(ProductMapper.class)); context.close();} }