SpringMVC启动报错:org.springframewor
2021-12-21 本文已影响0人
想象之中丶意料之外
-
大致报错信息:org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService';
报错图片
此问题排查点:
- spring配置文件中,<context:component-scan base-package> 能正常扫描到被注入进来的类【即:userService类需要被Spring容器管理】
- 确认:@Autowired注解、@Service注解是 springframework中的注解,别使用错误了。
- 确认:@Service注解,是使用在 Service接口实现类上【即@Service注解应该注解在UserServiceImpl类上,不是userService接口上】
- 确认:UserService接口是否有多个实现类,如果存在多个实现类,@Service注解需要取别名【@Service("别名")】,然后 注入userService时,需要使用@Qualifier("别名")来指定被注入的实现类是哪个。
上述排查点,排查后还是不行,那么按照下面方式,尝试一下
- 先确保UserService实现类中【UserServiceImpl】,没有注入其他类,比如UserDao类。
- 在确保UserService实现类中没有注入其他类后,尝试再次启动,看报不报错。
- 报错:上述点没排查干净。不报错:找到原因,UserService实现类中注入其他类失败导致。
原因
- 当UserService实现类中,存在注入其他类时,有可能是因为 UserService类在初始化时,注入其他的类失败,导致 UserService实现类初始化失败。
比如
- UserController 类中,注入了UserService类。UserService实现类中,注入了UserDao类。由于UserDao类在MyBatis配置时,出现错误了,不能自动生成UserDao接口代理类,导致UserServiceImpl类注入UserDao时失败,从而导致整个注入链条失败。
// controller类
public class UserController {
// 注入 userService类
@Autowired
private UserService userService;
}
// UserService实现类
@Service
public class UserServiceImpl implements UserService {
// 注入 UserDao类
@Autowired
private UserDao userDao;
}
- 其实报错信息中,最后一句话已经明确说明了:No qualifying bean of type 'blog.gk.dao.UserDao' available【没有类型为“blog.gk.dao.UserDao”的符合条件的bean可用】
补充UserDao接口不可用排查点:
- @Repository注解使用是否正确,即是否使用springframework的注解
- org.mybatis.spring.mapper.MapperScannerConfigurer类中,配置basePackage多个包时,UserDao接口是否存在重复。如果存在,可以使用@Repository("别名") 方法解决。
- 配置basePackage包路径时,当前UserDao接口是否能被包含在内,即确认是否能被扫描到。
- 确认:pom中加入了 spring-aop对aspectJ框架支持。即:spring-aspects 依赖,注意依赖版本与Spring框架版本是否存在不一致。
- 说明:Dao接口不能被注入,一般要确认其代理实现类是否有被创建,如果没有创建,那么就会无效。
使用 getBeanDefinitionNames方法,查看Spring容器中在管理哪些类
ApplicationContext context = new ClassPathXmlApplicationContext("spring/spring.xml");
String[] names = context.getBeanDefinitionNames();
for (String name : names) {
System.out.println("Spring管理的类:" + name);
}