org.springframework.beans.factory.NoSuchBeanDefinitionException
在我进行ssm整合的时候,遇到这个问题,是由于项目没有发现需要注入的bean(这个bean在报错日志中会显示出来),要解决此问题,我们要进行以下几步排错
- 此bean有没有注入spring容器中
- junit进行单元测试,测试是否可以从数据库中拿到相应的数据
@Test
public void test01(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//这里可以测试,是否可以拿到相应的bean,即spring中容器中是否有此bean
BookService bookServiceImpl = (BookService) context.getBean("bookServiceImpl");
List<Book> bookList = bookServiceImpl.queryAllBooks();
for (Book book : bookList) {
System.out.println(book);
}
}
- 如果以上两点没有问题,那么说明,问题不是出在底层,而是spring配置方面出了问题。
- springMVC整合的时候,要用到我们service 的bean,要考虑以下两点
- applicationContext.xml文件没有整合bean,有时候我们用多个子文件实现spring的配置时,要记得将子文件导入到applicationContext.xml这个文件中实现方式如下:
<?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-mvc.xml"/>
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
</beans>
- web.xml也需要配置文件,需要注意的是,我们关联的配置是applicationContext.xml这个spring
的总的配置文件,而不是spring配置的子文件。
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>