Java 如何在 spring 中使用 spring.xml 连接数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21949897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to connect database using spring.xml in spring?
提问by Poles
I'm new to the Spring framework and I was trying to do some basic database operations.I'm using oracle 10g for the database.I imported the jar files correctly. Previously, I used the same database configuration directly in JdbcDaoImplement.java and its working fine but when I put the database configuration in spring.xml file its throwing errors.Please tell me what is wrong?
我是 Spring 框架的新手,我正在尝试做一些基本的数据库操作。我使用 oracle 10g 作为数据库。我正确导入了 jar 文件。以前,我直接在JdbcDaoImplement.java中使用了相同的数据库配置并且它工作正常但是当我将数据库配置放在spring.xml文件中时它抛出错误。请告诉我出了什么问题?
My spring.xml includes:
我的 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:
矩形.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);
}
}
Next, JdbcDaoImplement .java
接下来,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();
}
}
}
}
and JdbcDemo .java
和 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());
}
}
and the error log is :
错误日志是:
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)
采纳答案by Muel
Question 1 answer
问题 1 个回答
Change:
改变:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource.class" autowire="byName">
To:
到:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" autowire="byName">
Ie remove the .class
! :)
即删除.class
!:)
Question 2 answer
问题 2 答案
In your main method, you're referring to DataSource
bean by id, but the JdbcDaoImplement
bean by type. Ie you're referring to two different Spring beans. Simple update your main method as follows:
在您的主要方法中,您是DataSource
按 id引用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());
}
回答by Evgeniy Dorofeev
Judging by exception type, you are missing spring-jdbc module
根据异常类型判断,您缺少 spring-jdbc 模块
回答by neel
<?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>