Service 和 Mapper 无法注入的常见原因与解决方案
一、最常见原因排查
1. 缺少注解
// Service 层
@Service // ← 必须有
public class UserServiceImpl implements UserService {
}
// Mapper 层
@Mapper // ← 必须有(MyBatis)
// 或者
@Repository // ← Spring 也能识别
public interface UserMapper {
}
2. 组件扫描范围问题
@SpringBootApplication
// 确保 scanBasePackages 覆盖了你的 Mapper/Service 所在包
@ComponentScan(basePackages = "com.example")
public class Application {
}
检查点:
- Service 和 Mapper 是否在
@SpringBootApplication所在包的子包下? - 如果 Mapper 在别的包,需要单独扫描:
@MapperScan("com.example.mapper")
二、MyBatis Mapper 特有排查
方案 1:加 @Mapper 注解
@Mapper
public interface UserMapper {
User findById(Long id);
}
方案 2:用 @MapperScan 批量扫描
@SpringBootApplication
@MapperScan("com.example.mapper") // ← 扫描整个 mapper 包
public class Application {
}
方案 3:在 Service 所在类上加 @Mapper
@Service
public class UserServiceImpl {
@Autowired
private UserMapper userMapper; // ← 确保能注入
}
三、Spring 注入相关排查
检查循环依赖
A → B → A ← 循环依赖,Spring 默认报错
解决:
// 用 @Lazy 延迟加载
@Autowired
@Lazy
private UserMapper userMapper;
检查是否是多数据源/配置类问题
// 确保配置类没有被 @Configuration 限制扫描范围
@Configuration
@MapperScan("com.example.mapper")
public class MybatisConfig {
}
四、快速排查清单
| 检查项 | 操作方法 |
|---|---|
| 包路径是否正确 | Service/Mapper 是否在主类子包下? |
| 注解是否遗漏 | 是否有 @Service / @Mapper / @Repository? |
| MapperScan 是否配置 | 是否加了 @MapperScan? |
| 组件扫描范围 | @ComponentScan 是否覆盖? |
| 循环依赖 | 是否有 A→B→A 的依赖? |
| 构造器注入 vs @Autowired | 是否有多个构造器导致歧义? |
| 接口实现是否匹配 | Service 接口和实现类是否正确对应? |
五、一个完整示例
// 1. 主类
@SpringBootApplication
@MapperScan("com.example.mapper") // ← 关键
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
// 2. Mapper
@Mapper // 或者不加,因为 @MapperScan 已经扫描
public interface UserMapper {
User selectById(Long id);
}
// 3. Service
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper; // ← 现在能注入了
public User getUser(Long id) {
return userMapper.selectById(id);
}
}
// 4. Controller
@RestController
public class UserController {
@Autowired
private UserService userService; // ← 也能注入了
}
六、常见错误信息对照
| 错误信息 | 可能原因 |
|---|---|
No qualifying bean of type 'XXXMapper' |
Mapper 没被扫描到 |
Could not autowire. No beans of 'XXXService' type found |
Service 没加 @Service |
Circular reference detected |
循环依赖 |
Expected single matching bean |
有多个实现类没指定 @Primary |
七、MyBatis-Plus 特殊处理
// MyBatis-Plus 需要加这个
@Configuration
@MapperScan("com.example.mapper")
public class MybatisPlusConfig {
}
确保 pom.xml 有正确依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3</version>
</dependency>
最可能的原因:你的 Mapper 接口没有被 @MapperScan 扫描到,或者 Service 类没有加 @Service 注解。 先检查这两项,90% 的问题能解决。