问题
Error creating bean with name 'bookController':
Unsatisfied dependency expressed through field 'bookService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'com.kai.service.BookService' 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=bookServiceImp)}
问题大概就是bookController类下找不到bookService对象(通过注解注入的value为bookServiceImp实例化的对象)
首先看下我的bookController类
@Controller
@RequestMapping("/book")
public class BookController {
//自动装配bean根据id
@Autowired
@Qualifier("bookServiceImp")
private BookService bookService;
@RequestMapping("/allBook")
public String list(Model model){
List<Books> books = bookService.queryAllBook();
model.addAttribute("books",books);
return "allBook";
}
}
spring-service.xml的bookServiceImp的bean注入
<bean id="bookServiceImp" class="com.kai.service.BookServiceImp">
<property name="mapper" ref="bookMapper"/>
</bean>
从这看注入没问题。然后去试一下是不是底层出错
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
BookServiceImp serviceImp = (BookServiceImp) context.getBean("bookServiceImp");
List<Books> books = serviceImp.queryAllBook();
for (Books book : books) {
System.out.println(book);
}
}
能查找到数据,底层没问题但是为什么bean不行呢。。。
肯定是spring配置出了问题才找不到bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd ">
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
三个都导入了呀。。。
原因:
先看下web.xml 圈起来的位置是spring-mvc.xml
DispatcherServlet仅仅导入了spring-mvc的配置没有导入service和dao的配置
无法进行调用生成!
解决办法
将上图位置中的spring-mvc.xml修改成applicationContext.xml即可