如何在spring中使用spring.xml连接数据库?

时间:2014-02-22 04:57:25

标签: java spring spring-jdbc

我是Spring框架的新手,我正在尝试做一些基本的数据库操作。我正在使用oracle 10g作为数据库。我正确地导入了jar文件。以前,我在JdbcDaoImplement.java中直接使用了相同的数据库配置,并且它的工作正常但是当我把数据库配置放在spring.xml文件中时抛出错误。请告诉我有什么问题?

我的spring.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"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

        <context:annotation-config></context:annotation-config>

        <context:component-scan base-package="org.spring"></context:component-scan>

        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" autowire="byName">
        <property name="driverClassName" value="oracle.jdbc.OracleDriver"></property>
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL"></property>
        <property name="username" value="system"></property>
        <property name="password" value="abcd"></property>
    </bean>
</beans>

Rect.java:

package org.spring.model;

public class Rect {

    private int id;
    private String name;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public Rect(int rectId, String rectName)
    {
        setId(rectId);
        setName(rectName);
    }


}

接下来,JdbcDaoImplement .java

package org.spring.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.spring.model.Rect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class JdbcDaoImplement {
    @Autowired
    private DataSource dataSource;



    public DataSource getDataSource() {
        return dataSource;
    }



    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }



    public Rect getRect(int rectId)
    {
        Connection conn=null;

        try
        {
            //String DriverName="oracle.jdbc.OracleDriver";
            //Class.forName(DriverName);
            //String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";
            //conn = DriverManager.getConnection(jdbcUrl, "system", "abcd");
            conn = dataSource.getConnection();
            PreparedStatement ps=conn.prepareStatement("SELECT * FROM RECTANGLE WHERE id=?");
            ps.setInt(1, rectId);

            Rect rect=null;
            ResultSet rs=ps.executeQuery();
            if(rs.next()==true)
            {
                rect=new Rect(rectId,rs.getString("name"));


            }
            rs.close();
            ps.close();
            return rect;
        }
        catch(Exception e)
        {
            throw new RuntimeException();
        }
        finally
        {
            try {
                conn.close();
            } catch (SQLException e) {
                //e.printStackTrace();

            }
        }
    }

}

和JdbcDemo .java

package org.spring;

import org.spring.dao.JdbcDaoImplement;
import org.spring.model.Rect;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class JdbcDemo {

    public static void main(String[] args) {
        ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
        JdbcDaoImplement dao=ctx.getBean("dataSource",JdbcDaoImplement.class);
        Rect rect=dao.getRect(1);
        System.out.println(rect.getName());
    }

}

,错误日志为:

INFO: Loaded JDBC driver: oracle.jdbc.OracleDriver
Exception in thread "main" org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'dataSource' must be of type [org.spring.dao.JdbcDaoImplement], but was actually of type [org.springframework.jdbc.datasource.DriverManagerDataSource]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:376)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:979)
    at org.spring.JdbcDemo.main(JdbcDemo.java:12)

3 个答案:

答案 0 :(得分:2)

问题1回答

变化:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource.class" autowire="byName">

要:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" autowire="byName">

即删除.class! :)

问题2回答

在main方法中,您通过id引用DataSource bean,而按类型引用JdbcDaoImplement bean。即你指的是两种不同的Spring bean。简单更新您的主要方法如下:

public static void main(String[] args) {
    ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
    JdbcDaoImplement dao=ctx.getBean(JdbcDaoImplement.class);
    Rect rect=dao.getRect(1);
    System.out.println(rect.getName());
}

答案 1 :(得分:-1)

根据异常类型判断,您缺少spring-jdbc模块

答案 2 :(得分:-1)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.h2.Driver"></property>
        <property name="url" value=" jdbc:h2:tcp://localhost/~/test2"></property>
        <property name="username" value="sa"></property>
        <property name="password" value="sa"></property>
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="hibernateProperties">
            <props>
                <!-- hibernate mapping to data definition lang -->
                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <property name="packagesToScan"><!-- Entities -->
            <list>
                <value>com.nt</value>
            </list>
        </property>
    </bean>

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>