MyBatis 整合 Spring 报: Could not find bean with name 'sqlSessionFactory'

Mina_young 发布于 2018/01/27 19:36
阅读 1K+
收藏 1

我们分为三部分来看:

  • 第一部分:报错信息 ;
  • 第二部分:源代码 ;
  • 第三部分:问题 ;

第一部分:报错信息:

java.lang.IllegalStateException: Failed to load ApplicationContext

java.lang.IllegalStateException: Failed to load ApplicationContext

	at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:94)
	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:15)
	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:231)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
	at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
	at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

 

Caused by: org.springframework.beans.factory.BeanCreationException

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [spring/spring-dao.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'dataSource' threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1518)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:838)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
	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)
	... 24 more

Caused by: org.springframework.beans.PropertyBatchUpdateException

Caused by: org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'dataSource' threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy
	at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:121)
	at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:75)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1514)
	... 40 more

 

第二部分:源代码

  1. 实体类 Seckill
    package org.seckill.entity;
    
    
    import java.util.Date;
    
    public class Seckill {
        private long seckillId ;
        private String name ;
        private int number ;
        private Date startTime ;
        private Date endTime ;
        private Date createTime ;
    
        public long getSeckillId() {
            return seckillId;
        }
    
        public void setSeckillId(long seckillId) {
            this.seckillId = seckillId;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getNumber() {
            return number;
        }
    
        public void setNumber(int number) {
            this.number = number;
        }
    
        public Date getStartTime() {
            return startTime;
        }
    
        public void setStartTime(Date startTime) {
            this.startTime = startTime;
        }
    
        public Date getEndTime() {
            return endTime;
        }
    
        public void setEndTime(Date endTime) {
            this.endTime = endTime;
        }
    
        public Date getCreateTime() {
            return createTime;
        }
    
        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }
    
        @Override
        public String toString() {
            return "Seckill{" +
                    "seckillId=" + seckillId +
                    ", name='" + name + '\'' +
                    ", number=" + number +
                    ", startTime=" + startTime +
                    ", endTime=" + endTime +
                    ", createTime=" + createTime +
                    '}';
        }
    }
    
  2. 实体接口类 SeckillDao
     

    package org.seckill.dao;
    
    import org.apache.ibatis.annotations.Param;
    import org.seckill.entity.Seckill;
    
    import java.util.Date;
    import java.util.List;
    
    public interface SeckillDao {
        /**
         * 减库存 ID、执行减库存的时间
         * 这里的 int ,如果返回值 >1 ,表示更新的记录行数,如果为0,表示没有更新成功
         * @Author May J Lee
         * @Description:
         * @Date 2018/1/11 15:18
         * @Param  * @param seckillId
         * @param killTime
         * @Return int
         */
        int reduceNumber(@Param("seckillId") long seckillId , @Param("killTime") Date killTime) ;
    
        /**
         * 根据 ID,查询秒杀商品信息
         * @Author May J Lee
         * @Description:
         * @Date 2018/1/11 15:18
         * @Param  * @param seckillId
         * @Return org.seckill.entity.Seckill
         */
        Seckill queryById(long seckillId) ;
    
        /**
         * 根据偏移量查询秒杀商品列表
         * offset 表示偏移量,limit表示需要取多少条记录
         * @Author May J Lee
         * @Description:
         * @Date 2018/1/11 15:24
         * @Param  * @param offet
         * @param limit
         * @Return java.util.List<org.seckill.entity.Seckill>
         */
        List<Seckill> queryAll(@Param("offset") int offset , @Param("limit") int limit) ;
    }
    
  3. 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>
    
        <!-- 配置全局属性 -->
        <settings>
            <!-- 使用 JDBC 的 getGeneratedKeys 获取数据库自增主键值 -->
            <setting name="useGeneratedKeys" value="true"/>
    
            <!-- 使用列别名替换列名 默认:true
                    Example: select name as title(实体中的属性名是title)from table ;
                    开启别名替换后,Mybatis 会自动把表中的 name 的值赋值给实体 title 的属性中 -->
            <setting name="useColumnLabel" value="trye" />
    
            <!-- 开启驼峰命名转换 : Table(create_time) -> Entity(createTime) -->
            <setting name="mapUnderscoreToCamelCase" value="true" />
    
        </settings>
    
    </configuration>
  4. Spring-dao.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"
           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">
    
    <!-- 配置整合 MyBatis 过程 -->
        <!-- 1、配置数据库相关参数 properties 的属性: $[url]-->
        <context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="NEVER"/>
    
        <!-- 2、数据库连接池 -->
        <bean id = "dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <!-- 配置连接池属性 -->
            <property name="driverClass" value="${jdbc.driver}"/>
            <property name="jdbcUrl" value="${jdbc.url}" />
            <property name="user" value="${jdbc.user}" />
            <property name="password" value="${jdbc.password}" />
    
            <!-- c3p0 连接池的[私有]属性 ,因为做高并发,c3p0默认属性不能满足我们的需求-->
            <property name="maxPoolSize" value="30" />
            <property name="minPoolSize" value="10" />
            <!-- 关闭连接后不自动 Commit -->
            <property name="autoCommitOnClose" value="false" />
            <!-- 获取连接超时时间 -->
            <property name="checkoutTimeout" value="1000" />
            <!-- 获取连接失败重试次数 -->
            <property name="acquireRetryAttempts" value="2" />
        </bean>
    
        <!-- 3、配置 SqlSessionFactory 对象 -->
        <bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean" >
            <!-- 注入数据库连接池 -->
            <property name="dataSource" ref="dataSource" />
            <!-- 配置 MyBatis 全局配置文件:mybatis-config.xml -->
            <property name="configLocation" value="classpath:mybatis-config.xml" />
            <!-- 扫描 entity 包,使用别名 (org.seckill.entity.Seckill) -> 可以统一转换成 Seckill -->
            <property name="typeAliasesPackage" value="org.seckill.entity" />
            <!-- 扫描 sql 配置文件: mapper 需要的 xml 文件 -->
            <property name="mapperLocations" value="classpath:mapper/*.xml" />
    
        </bean>
    
        <!-- 4、配置扫描 DAO 接口包 , 目的是动态实现 DAO 接口,并注入到 Spring 容器中
                这里的包扫描是自动运行的,不需要去引用,所以直接用 class-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" >
            <!-- 注入 SqlSessionFactory -->
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
            <!-- 给出扫描 DAO 接口包 -->
            <property name="basePackage" value="org.seckill.dao" />
        </bean>
    
    </beans>
  5. SeckillDao 接口的 Junit4单元测试
     

    package org.seckill.dao;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.seckill.entity.Seckill;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    
    import javax.annotation.Resource;
    
    import java.util.Date;
    import java.util.List;
    
    import static org.junit.Assert.*;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration({"classpath:spring/spring-dao.xml"})
    public class SeckillDaoTest {
    
        @Resource
        private SeckillDao seckillDao ;
    
    //现在就是测试 queryById 不通过,报最上面的错
        @Test
        public void queryById() throws Exception {
            long id = 1000 ;
            Seckill seckill = seckillDao.queryById(id) ;
            System.out.println(seckill.getName());
            System.out.println(seckill) ;
        }
    
        @Test
        public void queryAll() throws Exception {
            List<Seckill> seckills = seckillDao.queryAll(0 , 100) ;
            for (Seckill seckill : seckills) {
                System.out.println(seckill) ;
            }
        }
    
        @Test
        public void reduceNumber() throws Exception {
            Date killTime = new Date() ;
            int updateCount = seckillDao.reduceNumber(1000L , killTime) ;
            System.out.println("updateCount = " + updateCount) ;
        }
    
    
    
    }

 

第三部分:问题

  • 现在就是测试 queryById() 不通过,报第一部分的错
        @Test
        public void queryById() throws Exception {
            long id = 1000 ;
            Seckill seckill = seckillDao.queryById(id) ;
            System.out.println(seckill.getName());
            System.out.println(seckill) ;
        }

这是根本就没有注入进去吧 ?该怎么解决呢 ?

加载中
0
堪培拉的风
堪培拉的风

你这是几个意思?

0
y
youngkun
请配置事务
返回顶部
顶部