org.springframework.beans.factory.BeanCreationException:
org.springframework.beans.factory.BeanCreationException
經常犯這個錯誤,記錄下來,理一理xml檔案之間的關係
錯誤原因:config.xml檔案的mapper標籤引入了錯誤的檔案
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.mybatis.spring.mapper.MapperScannerConfigurer#0’ defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean ‘SqlSessionFactory’ while setting bean property ‘sqlSessionFactory’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘SqlSessionFactory’ defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: Failed to parse config resource: class path resource [config/config.xml]; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.lang.RuntimeException: Error parsing Mapper XML.
Mapper.xml檔案是寫SQL語句的,要講Mapper.xml檔案對映到config.xml檔案中
config.xml檔案內容:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "mybatis-3-config.dtd" > <configuration> <!--實體類取別名--> <typeAliases> <typeAlias type="com.lhm.entity.Person" alias="person"/> </typeAliases> <!--將Mapper.xml檔案引入config.xml檔案中--> <!--PersonDao.xml就是Mapper.xml檔案,與相應的DAO介面同名--> <mappers> <mapper resource="com/lhm/dao/PersonDao.xml"/> </mappers> </configuration>
將config.xml檔案對映到applicationContext.xml檔案中
applicationContext.xml檔案部分內容:
再將applicationContext.xml配置到web.xml檔案中
<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> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
mapper.xml -> config.xml -> applicationContext.xml -> web.xml