MapperScan和ComponentScan同时使用问题

@MapperScan:
1.首先了解@Mapper
    在接口上添加了@Mapper,在编译之后就会生成相应的接口实现类。
    不过需要在每个接口上面进行配置,为了简化开发,就有了 @MapperScan。

@MapperScan:

指定要变成实现类的接口所在的包,然后包下面的所有接口在编译之后都会生成相应的实现类。

@ComponentScan:
会自动扫描包路径下面的所有@Controller、@Service、@Repository、@Component 的类,并把符合扫描规则的类装配到spring容器中。

@MapperScan和@ComponentScan可以同时使用。


如果都是扫描的相同路径时,对于同一个接口,可能就会出现识别错误。比如

在springBoot项目的Application上面定义了

@MapperScan(basePackages = { "com" })
@SpringBootApplication
@SpringBootApplication包含了@ComponentScan。
在此项目下面有一个接口是com.xxInf,实现是
com.xxImpl在实现类上面通过@Service加入spring容器中
我们在注入的时候接口时
    @Autowired
    private com.xxInf xx;

可能识别的不是xxImpl,而去mybatis里面通过反射找绑定,这样就会出现BindingException错误

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)

所以在设计项目结构的时候要把mapper放到一个合适的位置,通过设置MapperScan的路径basePackages 好避免这种冲突

 

原文地址:https://www.cnblogs.com/grasp/p/10588996.html