问题遇到的现象和发生背景
使用ssm搭建项目,程序动后直接报500,提示BeanDefinationException.
报错信息如下
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookInfoController': Unsatisfied dependency expressed through field 'bookInfoService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.cy.service.BookInfoService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=bookInfoServiceImpl)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.cy.service.BookInfoService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=bookInfoServiceImpl)}
提示Bean对象创建失败,需要一个BookInfoService类型的Bean对象
相关代码如下
@Service
public class BookInfoServiceImpl implements BookInfoService {
@Resource
private BookInfoMapper bookInfoMapper;
@Override
public int addBookInfo(BookInfo bookInfo) {
return bookInfoMapper.addBookInfo(bookInfo);
}
@Override
public int deleteBookInfoById(int id) {
return bookInfoMapper.deleteBookInfoById(id);
}
@Override
public int updateBookInfo(BookInfo bookInfo) {
return bookInfoMapper.updateBookInfo(bookInfo);
}
@Override
public BookInfo queryForOne(int id) {
return bookInfoMapper.queryForOne(id);
}
@Override
public List<BookInfo> queryAll() {
return bookInfoMapper.queryAll();
}
}
解决思路
排查可能出现NoSuchBeanDefinitionException的几种情况
1.定义Bean的Id和getBean的Id不一致
2.使用注解进行对象的依赖注入时,没有开启相应的包扫描
3.检查相关注解是或使用正确
4.清除项目缓存,重启IDE
以上均无问题后,使用junit进行单元测试,查看两个Bean对象是否正常注入到容器中去,junit测试正常,数据可以正常查询。
相关代码如下:
@Test
public void test(){
ApplicationContext classPathXmlApplicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
BookInfoService bookInfoServiceImpl = (BookInfoService) classPathXmlApplicationContext.getBean(
"bookInfoServiceImpl");
for ( BookInfo bookInfo:bookInfoServiceImpl.queryAll()) {
System.out.println(bookInfo);
}
}
@Test
public void test1(){
ApplicationContext classPathXmlApplicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
BookInfoController bookInfoController = (BookInfoController) classPathXmlApplicationContext.getBean(
"bookInfoController");
System.out.println(bookInfoController.queryAll( ));
}
问题解决:
DispatcherServlet中配置的应该是整合后的配置文件,而非mvc子模块
总结
1.项目启动直接报错,大概率是web.xml的配置问题
2.项目出现问题时,应总览一下报错日志,切不可只看Root Cause
3.注意及时使用junit获取容器的方式进行测试
4.注意查看message