Tag Archives: Mybatis framework summary

Solve the problem that springboot does not scan @ repository

Problem: if you use @ repository annotation to annotate Dao layer alone, and do not use @ mapperscan scan, you will report an error when starting the project: field xxmapper in com.sms.shiro.service.impl.xxserviceimpl required a bean of type ‘com.sms.shiro.mapper.xxmapper’that could not be found.
, the difference between @ mapper and @ Repository:
1, @Repository is the annotation of spring family
2. When using @ mapper annotation, spring doesn’t know it, and the mapper injected into service by @ Autowired will be popular.

2、 Back to the question, it is clear that componentscan in springboot scans all annotated components under the starter package, but why can’t we find @ repository components
reason: the reason for this problem is that springboot automatically filters out interfaces and abstract classes during scanning, so the mapper interface modified by @ repository can’t be called a bean, so it can’t be injected into the service.

3、 Solution:

3.1 do not use @ repository, use @ mapper directly in the mapper layer interface, but if the project is large, it will be very troublesome.

3.2 if you want to use @ repository because springboot can’t scan mapper interface, then use @ mapperscan to scan all mapper interface packages on the launcher, such as: @ mapperscan ("com. SMS. Shiro. *. Mapper")

3.3 in fact, after using @ maperscan annotation to scan the mapper interface, the mapper interface does not need @ repository and @ mapper to register beans. However, if you want the project structure to be clear, after using @ maperscan annotation to scan, both @ repository and @ mapper can be used, and no error will be reported.