數據庫鏈接配置在jdbc.properties文件中,這種方式有一個最大的缺點,數據庫的配置信息對開發人員是徹底可見的,十分方便程序員刪庫跑路。spring配置具體以下:html
driver=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/test_table?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true& username=root password=root
<!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"/> </bean> <!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with username root and blank password. Change below if it's not the case --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${driver}"/> <!-- 基本屬性 url、user、password --> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="1"/> <property name="minIdle" value="1"/> <property name="maxActive" value="20"/> <!-- 配置獲取鏈接等待超時的時間 --> <property name="maxWait" value="60000"/> <!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000"/> <property name="validationQuery" value="SELECT 'x'"/> <property name="testWhileIdle" value="true"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <!-- 打開PSCache,而且指定每一個鏈接上PSCache的大小 --> <property name="poolPreparedStatements" value="false"/> <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/> <!-- 配置監控統計攔截的filters --> <property name="filters" value="stat"/> </bean>
以上簡單的配置就行了。java
JNDI須要配置spring和web容器(tomcat)相關配置文件(context.xml),這種配置的優勢是spring配置中只包含jndi的名稱,開發者看不到到具體數據庫的帳號和密碼,爲程序員刪庫跑路增長了難度。mysql
<Resource name="jdbc/erp" factory="com.alibaba.druid.pool.DruidDataSourceFactory" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://192.168.1.7:3306/test_table?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&" username="root" password="root" maxActive="50" maxWait="10000" removeabandoned="true" removeabandonedtimeout="60" logabandoned="false" filters="stat"/>
mysql-connector-java-5.1.38.jar druid-1.0.18.jar
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:comp/env/jdbc/erp"/> </bean>