当我使用 spring+springmvc+mybatis 设置我的项目时遇到一些问题
I get some issue when I set up my project with spring+springmvc+mybatis
道:
@Repository
public interface UserDao {
int searchAccount(String account);
int getPurview(User user);
}
服务:
public interface LoginService {
int judgeForUser(User user);
boolean searchAccount(String account);
}
服务实现:
@Service
public class LoginServiceImp implements LoginService {
@Resource
private UserDao userDao;
@Override
public boolean searchAccount(String account) {
if (userDao.searchAccount(account) == 1){
return true;
}
return false;
}
@Override
public int judgeForUser(User user) {
return userDao.getPurview(user);
}
}
映射:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.UserDao">
<select id="searchAccount" parameterType="String" resultType="int">
select 1 from users where account = #{account} limit 1
</select>
<select id="getPurview" parameterType="model.User">
select purview from users where account = #{account} and password = #{password}
</select>
</mapper>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!-- Spring MVC servlet -->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
mvc-servlet.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="controller"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver"
p:templateEngine-ref="templateEngine"
p:characterEncoding="UTF-8"/>
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolvers">
<set>
<ref bean="templateResolver"/>
</set>
</property>
</bean>
<bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver"
p:prefix="/WEB-INF/pages/"
p:templateMode="HTML"/>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonHttpMessageConverter"/>
</list>
</property>
</bean>
<bean id="jsonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:maxInMemorySize="3000000"/>
</beans>
spring-mybatis.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"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="dao"/>
<context:component-scan base-package="mapping"/>
<context:component-scan base-package="service"/>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:dbconfig.properties"/>
</bean>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"
p:filters="stat"
p:maxActive="8"
p:initialSize="1"
p:maxWait="60000"
p:minIdle="1"
p:timeBetweenEvictionRunsMillis="60000"
p:minEvictableIdleTimeMillis="30000"
p:validationQuery="SELECT 'x'"
p:testWhileIdle="true"
p:testOnBorrow="false"
p:testOnReturn="false"/>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mapping/*.xml"/>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<value>
helperDialect=mysql
</value>
</property>
</bean>
</array>
</property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
p:basePackage="dao"
p:sqlSessionFactoryBeanName="sqlSessionFactory"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
</beans>
当我运行它。它显示此错误,我不知道为什么它不能创建 bean?!
错误:
org.springframework.web.context.ContextLoader.initWebApplicationContext
Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'listViewServiceImp': Injection of resource
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'IListViewDao' defined in file
[/Users/Mario.Hu/Documents/mybatis/target/mybatis-1.0-SNAPSHOT/WEB-INF/classes/dao/IListViewDao.class]:
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 [spring-mybatis.xml]: Initialization of bean failed; nested
exception is org.springframework.beans.TypeMismatchException: Failed
to convert property value of type 'java.lang.String' to required type
'org.springframework.core.io.Resource[]' for property
'mapperLocations'; nested exception is
java.lang.IllegalArgumentException: Could not resolve resource
location pattern [classpath:mapping/.xml]: class path resource
[mapping/] cannot be resolved to URL because it does not exist at
org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:321)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'IListViewDao' defined in file
[/Users/Mario.Hu/Documents/mybatis/target/mybatis-1.0-SNAPSHOT/WEB-INF/classes/dao/IListViewDao.class]:
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 [spring-mybatis.xml]: Initialization of bean failed; nested
exception is org.springframework.beans.TypeMismatchException: Failed
to convert property value of type 'java.lang.String' to required type
'org.springframework.core.io.Resource[]' for property
'mapperLocations'; nested exception is
java.lang.IllegalArgumentException: Could not resolve resource
location pattern [classpath:mapping/.xml]: class path resource
[mapping/] cannot be resolved to URL because it does not exist at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sqlSessionFactory' defined in class
path resource [spring-mybatis.xml]: Initialization of bean failed;
nested exception is org.springframework.beans.TypeMismatchException:
Failed to convert property value of type 'java.lang.String' to
required type 'org.springframework.core.io.Resource[]' for property
'mapperLocations'; nested exception is
java.lang.IllegalArgumentException: Could not resolve resource
location pattern [classpath:mapping/.xml]: class path resource
[mapping/] cannot be resolved to URL because it does not exist at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
Caused by: org.springframework.beans.TypeMismatchException: Failed to
convert property value of type 'java.lang.String' to required type
'org.springframework.core.io.Resource[]' for property
'mapperLocations'; nested exception is
java.lang.IllegalArgumentException: Could not resolve resource
location pattern [classpath:mapping/.xml]: class path resource
[mapping/] cannot be resolved to URL because it does not exist at
org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:610)
Caused by: java.lang.IllegalArgumentException: Could not resolve
resource location pattern [classpath:mapping/*.xml]: class path
resource [mapping/] cannot be resolved to URL because it does not
exist at
org.springframework.core.io.support.ResourceArrayPropertyEditor.setAsText(ResourceArrayPropertyEditor.java:116)
27-May-2017 23:35:23.398 严重 [RMI TCP Connection(2)-127.0.0.1]
org.apache.catalina.core.StandardContext.startInternal One or more
listeners failed to start. Full details will be found in the
appropriate container log file 27-May-2017 23:35:23.420 严重 [RMI TCP
Connection(2)-127.0.0.1]
org.apache.catalina.core.StandardContext.startInternal Context []
startup failed due to previous errors
为什么?我跟随其他人构建这些代码!但它对我不起作用!
从错误消息来看,似乎无法在您的类路径中找到资源目录映射。
或者在 spring-mybatis.xml 中使用以下内容(注意额外的 *)
<property name="mapperLocations" value="classpath*:mapping/*.xml"/>
如果找不到,这不会return异常。检查此 link
中的更多差异
道:
@Repository
public interface UserDao {
int searchAccount(String account);
int getPurview(User user);
}
服务:
public interface LoginService {
int judgeForUser(User user);
boolean searchAccount(String account);
}
服务实现:
@Service
public class LoginServiceImp implements LoginService {
@Resource
private UserDao userDao;
@Override
public boolean searchAccount(String account) {
if (userDao.searchAccount(account) == 1){
return true;
}
return false;
}
@Override
public int judgeForUser(User user) {
return userDao.getPurview(user);
}
}
映射:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.UserDao">
<select id="searchAccount" parameterType="String" resultType="int">
select 1 from users where account = #{account} limit 1
</select>
<select id="getPurview" parameterType="model.User">
select purview from users where account = #{account} and password = #{password}
</select>
</mapper>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!-- Spring MVC servlet -->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
mvc-servlet.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="controller"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver"
p:templateEngine-ref="templateEngine"
p:characterEncoding="UTF-8"/>
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolvers">
<set>
<ref bean="templateResolver"/>
</set>
</property>
</bean>
<bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver"
p:prefix="/WEB-INF/pages/"
p:templateMode="HTML"/>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonHttpMessageConverter"/>
</list>
</property>
</bean>
<bean id="jsonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:maxInMemorySize="3000000"/>
</beans>
spring-mybatis.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"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="dao"/>
<context:component-scan base-package="mapping"/>
<context:component-scan base-package="service"/>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:dbconfig.properties"/>
</bean>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"
p:filters="stat"
p:maxActive="8"
p:initialSize="1"
p:maxWait="60000"
p:minIdle="1"
p:timeBetweenEvictionRunsMillis="60000"
p:minEvictableIdleTimeMillis="30000"
p:validationQuery="SELECT 'x'"
p:testWhileIdle="true"
p:testOnBorrow="false"
p:testOnReturn="false"/>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mapping/*.xml"/>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<value>
helperDialect=mysql
</value>
</property>
</bean>
</array>
</property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
p:basePackage="dao"
p:sqlSessionFactoryBeanName="sqlSessionFactory"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
</beans>
当我运行它。它显示此错误,我不知道为什么它不能创建 bean?!
错误:
org.springframework.web.context.ContextLoader.initWebApplicationContext Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'listViewServiceImp': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IListViewDao' defined in file [/Users/Mario.Hu/Documents/mybatis/target/mybatis-1.0-SNAPSHOT/WEB-INF/classes/dao/IListViewDao.class]: 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 [spring-mybatis.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.core.io.Resource[]' for property 'mapperLocations'; nested exception is java.lang.IllegalArgumentException: Could not resolve resource location pattern [classpath:mapping/.xml]: class path resource [mapping/] cannot be resolved to URL because it does not exist at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:321) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IListViewDao' defined in file [/Users/Mario.Hu/Documents/mybatis/target/mybatis-1.0-SNAPSHOT/WEB-INF/classes/dao/IListViewDao.class]: 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 [spring-mybatis.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.core.io.Resource[]' for property 'mapperLocations'; nested exception is java.lang.IllegalArgumentException: Could not resolve resource location pattern [classpath:mapping/.xml]: class path resource [mapping/] cannot be resolved to URL because it does not exist at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [spring-mybatis.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.core.io.Resource[]' for property 'mapperLocations'; nested exception is java.lang.IllegalArgumentException: Could not resolve resource location pattern [classpath:mapping/.xml]: class path resource [mapping/] cannot be resolved to URL because it does not exist at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564) Caused by: org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.core.io.Resource[]' for property 'mapperLocations'; nested exception is java.lang.IllegalArgumentException: Could not resolve resource location pattern [classpath:mapping/.xml]: class path resource [mapping/] cannot be resolved to URL because it does not exist at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:610) Caused by: java.lang.IllegalArgumentException: Could not resolve resource location pattern [classpath:mapping/*.xml]: class path resource [mapping/] cannot be resolved to URL because it does not exist at org.springframework.core.io.support.ResourceArrayPropertyEditor.setAsText(ResourceArrayPropertyEditor.java:116) 27-May-2017 23:35:23.398 严重 [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file 27-May-2017 23:35:23.420 严重 [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal Context [] startup failed due to previous errors
为什么?我跟随其他人构建这些代码!但它对我不起作用!
从错误消息来看,似乎无法在您的类路径中找到资源目录映射。
或者在 spring-mybatis.xml 中使用以下内容(注意额外的 *)
<property name="mapperLocations" value="classpath*:mapping/*.xml"/>
如果找不到,这不会return异常。检查此 link
中的更多差异