1.项目根目录下建立conf,lib目录,将spring相关包coop到lib中并导入,建立2个文件jdbc.properties,bean.xml
jdbc.properties:
[
html]
driverClassName=org.gjt.mm.
mysql.Driver
url=jdbc:mysql://localhost:3306/test useUnicode=true&characterEncoding=UTF-8
username=root
password=root
initialSize=1
maxActive=300
maxIdle=2
minIdle=1
bean.xml:
[html]
< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
destroy-method="close">
把我们定义的数据源注入到DataSourceTransactionManager类的属性dataSource中
-->
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
jdbc 不用说了,bean.xml是主要的配置文件主要有2个部分
(1) 为配置数据源,从jdbc.properties读取。
如果数据源有多个,只要复制这一部分就可以了
(2) 部分,这部分为配置自己的业务service,比如我配置的一个
id 为唯一的标识, class是类路径,name="dataSource"是类中的属性,ref就是要用到的数据源id
2.配置文件写好后,就可以写数据库读写的部分了,主要管理在DBServer.java 中
[java]
package com.spring.db;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DBServer {
private PlayerService playerService;
private static DBServer instance = null;
public static DBServer getInstance() {
if (instance == null) {
instance = new DBServer();
}
return instance;
}
public DBServer(){
ApplicationContext act = new ClassPathXmlApplicationContext("bean.xml");
playerService = (PlayerService) act.getBean("playerService");
}
public PlayerService getPlayerService() {
return playerService;
}
public void setPlayerService(PlayerService playerService) {
this.playerService = playerService;
}
}
为了方便,就直接在构造函数里面初始化了,代码也容易理解
playerService = (PlayerService) act.getBean("p