1. 程式人生 > >Spring中使用bean配置資料庫

Spring中使用bean配置資料庫

摘自李剛《輕量級JavaEE企業應用實戰》

平時我們配置資料庫資訊是通過hibernate.cfg.xml來配置,其實也可以用bean來配置連線池的(比如說c3p0),現在我們就用Spring的bean來配置一次資料庫連線池吧
首先我們在beans.xml檔案中建立一個bean

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver"
/> <property name="jdbcUrl" value="jdbc:mysql://localhost/sm"/> <property name="user" value="root"/> <property name="password" value="abc"/> <property name="maxPoolSize" value="200"/> <property name="minPoolSize" value="2"/> <property
name="initialPoolSize" value="2"/> <property name="maxIdleTime" value="200"/> </bean>

之後使用這個bean

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        DataSource dataSource = applicationContext.getBean("dataSource", DataSource.class
); Connection connection; try { connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement("insert into sm_test values(null,?,?,?)"); statement.setTimestamp(1, new Timestamp(System.currentTimeMillis())); statement.setLong(2, (long)2); statement.setLong(3, (long)3); statement.executeUpdate(); if(statement != null) { statement.close(); } if(connection != null) { connection.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }

程式執行的效果是往wx_test表中插入了一條資料,程式碼中DataSource就是通過Spring來獲取的