最近打算做一个项目,照着网上在打架,结果在<property name="dataSource" ref ="dataSource" />的时候,ref里面的值一直报错,报的cannot resolve bean dataSource Spring XML model validation<?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:tx="http://www.springframework.org/schema/tx"
       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/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 扫描service包下所有使用注解的类型 -->
    <context:component-scan base-package="com.service" />    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref ="dataSource" />
    </bean>
    <!-- 配置基于注解的声明式事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

解决方案 »

  1.   

    这个ref属性的意思是:引用bean,你这里就是引用dataSource这个bean
    引用的bean也必须是由spring管理的,通常来说dataSource就是数据源的bean,这个要你自己配置bean组件你在xml文件里加上这个bean配置<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  <!-- 这里的class配置为数据源的类型,这里的basicDataSource是apache的数据源,根据你自己的需求可以修改为其他的,没有特殊要求可以不改 -->
        <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />  <!-- 数据库的驱动名,这个根据你用的数据库类型自己百度 -->
        <property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=spring" />  <!-- 数据库的连接地址,注意格式不同数据库格式略有不同,自行百度 -->
        <property name="username" value="sa" />  <!-- 数据库的用户名 -->
        <property name="password" value="********" />  <!-- 数据库的密码 -->
    </bean>