Spring DBCP用xml和properties2種格式配置DataSource
阿新 • • 發佈:2017-11-02
oid per ace word spring mon cti tar .exe Spring提供數據庫連接池:DBCP配置DataSource並且獲取連接完成數據庫操作:
Spring幫助文檔的地址:
http://static.springsource.org/spring/docs/2.5.6/reference/beans.html#beans-value-element
以下內容需要導入的jar包:
commons-dbcp.jar
commons-pool.jar
mysql-connector-java-5.0-nightly-20071116-bin.jar
1. 首先在容器內配置數據源
[html] view plain copy
- <!-- 配置數據源 -->
- <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
- <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
- <property name="url" value="jdbc:mysql://localhost:3306/sms"/>
- <property name="username" value="root"/>
- <property name="password" value="root"/>
- </bean>
- @Component("userService")
- public class UserServiceImpl implements UserService{
- private UserDao userDao;
- public void setUserDao(UserDao userDao) {
- this.userDao = userDao;
- }
- @Resource //resource註入
- private DataSource myDataSource;
- public DataSource getMyDataSource() {
- return myDataSource;
- }
- public void setMyDataSource(DataSource myDataSource) {
- this.myDataSource = myDataSource;
- }
- //在下面方法前面加邏輯
- public void save(){
- try{
- //拿到連接執行操作
- Connection conn = myDataSource.getConnection();
- conn.createStatement().execute("insert into dept values(‘6‘,‘bumen2‘)");
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- }
- @Test
- public void test01() {
- BeanFactory applicationContext = new ClassPathXmlApplicationContext(
- "beans.xml");
- UserService user = (UserService) applicationContext.getBean("userService");
- user.save();
- }
- jdbc.driverClassName=com.mysql.jdbc.Driver
- jdbc.url=jdbc:mysql://localhost:3306/sms
- jdbc.username=root
- jdbc.password=root
- <!-- placeholder 占位符 -->
- <bean
- class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="locations">
- <value>classpath:jdbc.properties</value>
- </property>
- </bean>
- <bean id="dataSource" destroy-method="close"
- class="org.apache.commons.dbcp.BasicDataSource">
- <property name="driverClassName" value="${jdbc.driverClassName}" />
- <property name="url" value="${jdbc.url}" />
- <property name="username" value="${jdbc.username}" />
- <property name="password" value="${jdbc.password}" />
- </bean>
Spring DBCP用xml和properties2種格式配置DataSource