spring+springmvc整合mabytis时mapper注入失败问题解决方法

好久不搭架构,今天使用spring+springmvc整合mabytis的时候,坑爹的两个问题发生了。

花了一晚上解决这两个问题。现在将错误经验总结分享下,避免以后遇到坑继续往里跳。

1. 单元测试的时候,单元测试失败报错: A ServletContext is required to configure default servlet handling

十月 28, 2016 9:03:33 下午 org.springframework.context.support.GenericApplicationContext refresh
警告: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
  at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
  at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
  at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
  at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
  at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
  at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
  at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125)
  at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
  at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:109)
  at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:261)
  at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:68)
  at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:86)
  at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:72)
  at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
  at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
  at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:200)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:259)
  at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:261)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:219)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
  at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
  at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
  at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
  at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
  at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
  at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
  at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
  at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
  ... 42 more

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>Archetype Created Web Application</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <!-- 指定Spring初始上下文环境-指定spring-core配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring_ynyn_dependence.xml</param-value>
  </context-param>

  <!-- 字符编码过滤器 -->
  <filter>
    <filter-name>characterEncoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- spring-mvc分发器配置并指定spring-mvc配置文件 -->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>
      org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
        classpath:spring-mvc.xml
      </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <filter>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <servlet-name>dispatcherServlet</servlet-name>
  </filter-mapping>
</web-app>

资源以及配置文件都放在src/main/respources目录下。

springMVC的配置文件spring-mvc.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:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
  xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task"
  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
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc.xsd
      http://www.springframework.org/schema/util
      http://www.springframework.org/schema/util/spring-util-3.1.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
      http://www.springframework.org/schema/task
      http://www.springframework.org/schema/task/spring-task.xsd">

  <context:component-scan base-package="org.byron4j.ynyn.*" >
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
  </context:component-scan> 

  <!-- 默认的注解映射的支持 -->
  <mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
      <bean class="org.springframework.http.converter.StringHttpMessageConverter">
        <constructor-arg value="UTF-8" />
      </bean>
      <bean
        class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
        <property name="supportedMediaTypes" value="application/json;charset=UTF-8" />
        <property name="features">
          <array>
            <value>WriteMapNullValue</value>
            <value>WriteNullStringAsEmpty</value>
          </array>
        </property>
      </bean>
    </mvc:message-converters>
  </mvc:annotation-driven>

  <!-- 静态资源映射 -->
  <mvc:resources mapping="/js/**" location="/js/" />
  <mvc:resources mapping="/css/**" location="/css/" />
  <mvc:resources mapping="/images/**" location="/images/" />
  <!-- 当上面要访问的静态资源不包括在上面的配置中时,则根据此配置来访问 -->
  <mvc:default-servlet-handler />

  <!--对模型视图名称的解析,即在模型视图名称添加前后缀 -->
  <bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass"
      value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/"></property>
    <property name="suffix" value=".jsp"></property>
  </bean>
</beans>

sprin框架的配置文件spring_ynyn_dependence.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:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:util="http://www.springframework.org/schema/util"
  xmlns:task="http://www.springframework.org/schema/task"
  xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.1.xsd
      http://www.springframework.org/schema/util
      http://www.springframework.org/schema/util/spring-util-3.1.xsd
      http://www.springframework.org/schema/task
      http://www.springframework.org/schema/task/spring-task.xsd">
  <util:properties id="valueSettings" location="classpath:globalConfig.properties" />

  <context:component-scan base-package="org.byron4j.ynyn.*" >
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
  </context:component-scan>

  <!--引入定时任务注解驱动,可以在应用中使用@Scheduled注解开发定时任务-->
  <task:annotation-driven />

  <!--引入数据源配置,包括mybatis相关的配置-->
  <import resource="classpath*:byron4j_ynyn_datasource.xml"/>
</beans>

数据源配置文件byron4j_ynyn_datasource.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:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.1.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="configLocation" value="classpath:byron4j_ynyn_mybatis-config.xml" />
    <!--我的项目的表的mapper.xml文件放在src/main/resources目录下-->
    <property name="mapperLocations" value="classpath*:sqlmap/*.xml" />
    <property name="dataSource" ref="dataSource" />
  </bean>

  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="org.byron4j.ynyn.mapper" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
  </bean>

  <!-- 事务管理 -->
  <bean id="myTxManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
  </bean>

  <tx:annotation-driven transaction-manager="myTxManager" />

  <!--这里使用的是sqlite数据库,是一种文件数据库,用户名密码的账户必须拥有可以读写ynyn.sqlite文件的权限-->
  <bean id="dataSource"
     class="org.apache.commons.dbcp.BasicDataSource"
     destroy-method="close">
    <property name="driverClassName" value="org.sqlite.JDBC"/>
    <property name="url" value="jdbc:sqlite:E:\ynyn.sqlite"/>
    <property name="username" value="username"/>
    <property name="password" value="password"/>
    <!--maxActive: 最大连接数量-->
    <property name="maxActive" value="200"/>
    <!--minIdle: 最小空闲连接-->
    <property name="minIdle" value="10"/>
    <!--maxIdle: 最大空闲连接-->
    <property name="maxIdle" value="50"/>
    <!--initialSize: 初始化连接-->
    <property name="initialSize" value="50"/>
    <!-- 连接被泄露时是否打印 -->
    <property name="logAbandoned" value="true"/>
    <!--removeAbandoned: 是否自动回收超时连接-->
    <property name="removeAbandoned" value="true"/>
    <!--removeAbandonedTimeout: 超时时间(以秒数为单位)-->
    <property name="removeAbandonedTimeout" value="180"/>
    <!--maxWait: 超时等待时间以毫秒为单位 1000等于60秒-->
    <property name="maxWait" value="1000"/>
    <!-- 在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位. -->
    <property name="timeBetweenEvictionRunsMillis" value="10000"/>
    <!-- 在每次空闲连接回收器线程(如果有)运行时检查的连接数量 -->
    <property name="numTestsPerEvictionRun" value="10"/>
    <!-- 1000 * 60 * 30 连接在池中保持空闲而不被空闲连接回收器线程-->
    <property name="minEvictableIdleTimeMillis" value="10000"/>
    <property name="validationQuery" value="SELECT 1 LIMIT 1 "/>
  </bean>

</beans>

mybatis配置文件byron4j_ynyn_mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-config.dtd">
  <configuration>

</configuration>

单元测试基类BaseMockitoTestCase.java

src/test/Java目录下:

package org.byron4j.ynyn.base;

import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Mock测试类基类--配置文件载入类
 *
 * @ClassName: BaseSpringTestCase
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring_ynyn_dependence.xml" })
public class BaseMockitoTestCase {
  @Before
  public void beforeInvoke() {
    System.out.println("调用前工作....");
    MockitoAnnotations.initMocks(this);
  }

  @After
  public void afterInvoke() {
    System.out.println("调用完成.");
  }

}

单元测试类StudentTest.java出问题了

package org.byron4j.ynyn.dbtest;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import org.byron4j.ynyn.base.BaseMockitoTestCase;
import org.byron4j.ynyn.mapper.TaskerMapper;
import org.byron4j.ynyn.mode.Tasker;

public class StudentTest extends BaseMockitoTestCase{

  @Autowired
  StudentMapper studentMapper;

  @Test
  public void selectTest4Success(){
    Student record = new Student();
    record.setId(1);
    Student resultStudent = studentMapper.selectByPrimaryKey(record);
    System.out.println(resultStudent);;
  }
}

执行单元测试的时候,报错了警告: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘defaultServletHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method ‘defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling

这时候去检查spring-core和springMVC的两个配置文件,异常提示信息大意是ServletContext需要配置默认servlet处理映射器。一脸懵逼。。。最后发现是两个配置文件的context和包扫描配置有问题,springServlet上下文应该在spring核心配置中( spring_ynyn_dependence.xml )处理,需要使用 <context:annotation-config /> 进行配置。调整后的配置是:

1.sprin框架的配置文件spring_ynyn_dependence.xml调整

将以下配置内容
<context:component-scan base-package="org.byron4j.ynyn.*" >
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
  </context:component-scan>
替换为:
<context:annotation-config />

2.springMVC的配置文件spring-mvc.xml调整

<context:component-scan base-package="com.crfchina.mcp.*" >
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
  </context:component-scan> 

再次执行单元测试,OK。

二. mapper注入失败使用@Autowired注解: nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.byron4j.mcp.mapper.TaskerMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

警告: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'taskListenerConfigController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.byron4j.mcp.service.TaskListenerConfigService org.byron4j.mcp.controller.TaskListenerConfigController.taskListenerConfigService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'taskListenerConfigServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.byron4j.mcp.mapper.TaskerMapper org.byron4j.mcp.service.impl.TaskListenerConfigServiceImpl.taskerMapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.byron4j.mcp.mapper.TaskerMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
  at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
  at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
  at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
  at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
  at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
  at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
  at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
  at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
  at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
  at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
  at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
  at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
  at javax.servlet.GenericServlet.init(GenericServlet.java:158)
  at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
  at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
  at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
  at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5231)
  at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5518)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
  at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
  at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
  at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649)
  at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1081)
  at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1877)
  at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
  at java.util.concurrent.FutureTask.run(FutureTask.java:266)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.byron4j.mcp.service.TaskListenerConfigService org.byron4j.mcp.controller.TaskListenerConfigController.taskListenerConfigService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'taskListenerConfigServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.byron4j.mcp.mapper.TaskerMapper org.byron4j.mcp.service.impl.TaskListenerConfigServiceImpl.taskerMapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.byron4j.mcp.mapper.TaskerMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
  at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
  at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
  at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
  ... 33 more

解决第一个问题,单元测试后,部署该项目启动时,疯狂报错nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.byron4j.mcp.mapper.TaskerMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}。多次检查,发现springMVC配置文件中也需要加载mybatis配置,前面我仅仅在spring上下文核心配置文件(spring_ynyn_dependence.xml)中做了配置。

在spring-mvc.xml文件最后引入加载mybatis配置:

<import resource="classpath*:byron4j_ynyn_datasource.xml"/>

重新部署应用启动服务无措,发起请求验证OK。

(0)

相关推荐

  • spring+springmvc整合mabytis时mapper注入失败问题解决方法

    好久不搭架构,今天使用spring+springmvc整合mabytis的时候,坑爹的两个问题发生了. 花了一晚上解决这两个问题.现在将错误经验总结分享下,避免以后遇到坑继续往里跳. 1. 单元测试的时候,单元测试失败报错: A ServletContext is required to configure default servlet handling 十月 28, 2016 9:03:33 下午 org.springframework.context.support.GenericAppl

  • Spring Boot 整合mybatis 使用多数据源的实现方法

    前言 本篇教程偏向实战,程序猿直接copy代码加入到自己的项目中做简单的修修改改便可使用,而对于springboot以及mybatis不在此进行展开介绍,如有读者希望了解可以给我留言,并持续关注,我后续会慢慢更新.(黑色区域代码部分,安卓手机可手动向左滑动,来查看全部代码) 整合 其实整合很简单,如果是用gradle的话,在build.gradle文件里加入 compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.1')

  • Spring Boot整合JPA使用多个数据源的方法步骤

    介绍 JPA(Java Persistence API)Java 持久化 API,是 Java 持久化的标准规范,Hibernate 是持久化规范的技术实现,而 Spring Data JPA 是在 Hibernate 基础上封装的一款框架. 第一次使用 Spring JPA 的时候,感觉这东西简直就是神器,几乎不需要写什么关于数据库访问的代码一个基本的 CURD 的功能就出来了.在这篇文章中,我们将介绍 Spring Boot 整合 JPA 使用多个数据源的方法. 开发环境: Spring B

  • mysql 登录时闪退的问题解决方法

    mysql 登录时闪退的问题解决方法 之前mysql用着好着,可是今天在启动mysql后输入密码出现了闪退,在任务管理器中发现mysql服务没有启动,当手动启动时提示拒绝访问.在网上查找原因发现问题所在. 问题原因:mysql服务没有安装. 解决办法: 在cmd操作下找到mysql的安装目录(注意要用管理员身份运行cmd) 在 mysql bin目录下 以管理员的权限 执行 mysqld -install命令 然后仍然以管理员的权限 net start mysql 开启Mysql服务了. 输入m

  • Spring运行时手动注入bean的方法实例

    有时候,会有这样一个需求,在程序运行时动态生成的对象,需要注入到Spring容器中进行管理. 下面是获取Bean以及注入Bean的工具类 import org.springframework.beans.BeansException; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinit

  • spring boot整合quartz实现多个定时任务的方法

    最近收到了很多封邮件,都是想知道spring boot整合quartz如何实现多个定时任务的,由于本人生产上并没有使用到多个定时任务,这里给个实现的思路. 1.新建两个定时任务,如下: public class ScheduledJob implements Job{ @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("sched

  • spring boot整合jsp及设置启动页面的方法

    前言 这几天在集中学习Spring boot+Shiro框架,因为之前view层用jsp比较多,所以想在spring boot中配置jsp,但是spring boot官方不推荐使用jsp,因为jsp相对于一些模板引擎,性能都比较低,官方推荐使用thymeleaf,但是Spring boot整合jsp的过程已经完成,在这里记录一下. 本文基于springboot2.0.4最新版本 spring官方推荐Thymeleaf但是还是有很多javaweb朋友习惯使用jsp虽然现在jsp有点out.本节教程

  • Docker Desktop常见的几种启动失败问题解决方法

    目录 报错1,Error:Failed to restart 报错2,Error invoking remote method 'desktop-go-backend':[object Object] 报错3,无错误信息,一直卡在 Docker Desktop starting... 报错4,在Ubuntu for windows 中执行docker命令提示未找到 报错5,LxssManager无法启动,处于停止状态 总结 报错1,Error:Failed to restart 点Quit 然后

  • 解决Spring Cloud中Feign/Ribbon第一次请求失败的方法

    前言 在Spring Cloud中,Feign和Ribbon在整合了Hystrix后,可能会出现首次调用失败的问题,要如何解决该问题呢? 造成该问题的原因 Hystrix默认的超时时间是1秒,如果超过这个时间尚未响应,将会进入fallback代码.而首次请求往往会比较慢(因为Spring的懒加载机制,要实例化一些类),这个响应时间可能就大于1秒了.知道原因后,我们来总结一下解决放你. 解决方案有三种,以feign为例. 方法一 hystrix.command.default.execution.

  • spring中通过ApplicationContext getBean获取注入对象的方法实例

    用SpringContextUtil实现ApplicationContextAware package util; import java.util.Locale; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; pub

随机推荐