项目中用到了mybatis-plus。springboot集成mybatis-plus项目,通常会使用内置mybatis工具包的org.mybatis.spring.annotation.MapperScan注解,来完成Mapper类的扫描。MapperScan注解源码见下。
- public @interface MapperScan {
-
- /**
- * Alias for the {@link #basePackages()} attribute. Allows for more concise
- * annotation declarations e.g.:
- * {@code @MapperScan("org.my.pkg")} instead of {@code @MapperScan(basePackages = "org.my.pkg"})}.
- *
- * @return base package names
- */
- String[] value() default {};
-
- /**
- * Base packages to scan for MyBatis interfaces.
- * Note that only interfaces with at least one method will be registered; concrete classes will be ignored.
- * 翻译:用于扫描MyBatis接口的基础package(可多个)。请注意,只有具有至少一个方法的接口才会被注册;具体类将被忽略。
- *
- * @return base package names for scanning mapper interface
- */
- String[] basePackages() default {};
- }
项目使用这个MapperScan注解来决定扫描Mapper类所在的包。见下方MybatisPlusConfig配置类。
- package springtrans;
-
- import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
-
- @Configuration
- @MapperScan(value={"springtrans.**.mapper"})
- public class MybatisPlusConfig {
-
- /**
- * 分页插件
- */
- @Bean
- public PaginationInterceptor paginationInterceptor() {
- // 设置sql的limit为无限制,默认是500
- return new PaginationInterceptor().setLimit(-1);
- }
-
- }
近期在对项目中的结算代码进行优化,这里,我们先设定结算表仓储类名称是SettlementMapper。这次重构涉及到需要屏蔽SettlementMapper的update操作。实现途径是将SettlementMapper从现有package移出去,并且让mybatis-plus追加扫描SettlementMapper所在的package。
于是,修改MybatisPlusConfig中MapperScan的value值。
- @Configuration
- @MapperScan(value={"springtrans.**.mapper, springtrans.transtest.manager"})
- public class MybatisPlusConfig {
- ...
- }
不料,运行testcase出现了下面的NoSuchBeanDefinitionException异常。
- org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'springtrans.transtest.entity.OrderMapper' available:
- expected at least 1 bean which qualifies as autowire candidate.
- Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
- at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695)
- at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253)
- at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
- at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:636)
- ... 44 more
聪明的你,是不是看出了其中的端倪?
哈哈,我竟然犯了如此低级失误。
正确姿势是:
- @Configuration
- @MapperScan(value={"springtrans.**.mapper", "springtrans.transtest.manager"})
- public class MybatisPlusConfig {
- ...
- }
EOF,感谢阅读!