如何在Spring中通过XML定义MySql数据源bean

时间:2012-09-29 23:47:38

标签: spring javabeans datasource definition

我查看了文档来定义bean。我只是不清楚用于Mysql数据库的类文件。任何人都可以填写下面的bean定义吗?

<bean name="dataSource" class="">
    <property name="driverClassName" value="" />
    <property name="url" value="mysql://localhost/GameManager" />
    <property name="username" value="gamemanagertest" />
    <property name="password" value="1" />
</bean>

3 个答案:

答案 0 :(得分:41)

<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/GameManager" />
    <property name="username" value="gamemanagertest" />
    <property name="password" value="1" />
</bean>

http://docs.spring.io/spring-data/jdbc/docs/1.1.0.M1/reference/html/orcl.datasource.html

答案 1 :(得分:6)

使用此课程org.springframework.jdbc.datasource.DriverManagerDataSource - DriverManagerDataSource。作为最佳实践,如果我们将数据库值隔离到.properties文件并将其配置为spring servlet xml配置,则更好。在下面的示例中,属性存储为键值对,我们使用相应的value访问key

<强> 的applicationContext-dataSource.xml

<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-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
    <property name="connectionCachingEnabled" value="true"/>
</bean>

<context:property-placeholder location="classpath:jdbc.properties"/>

jdbc.propeties 档案:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sample_db
jdbc.username=root
jdbc.password=sec3ret

答案 2 :(得分:5)

两个答案都适合该问题。但是,仅在FYI中,如果您要使用 DriverManagerDataSource 作为数据源,对数据源bean的每次调用都会创建与数据库的新连接,不建议将其用于生产,甚至不合并连接。

如果需要连接池,请考虑Apache Commons DBCP

<bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/GameManager" />
    <property name="username" value="gamemanagertest" />
    <property name="password" value="1" />
    <property name="initialSize" value="2" />
    <property name="maxActive" value="5" />
</bean>

initialSizemaxActive在合并相关属性的位置。

要使用此功能,请确保路径中有required jar