1. 程式人生 > >使用Spring框架來管理模板類

使用Spring框架來管理模板類

1. 剛才編寫的程式碼使用的是new的方式,應該把這些類交給Spring框架來管理。
2. 修改的步驟如下
    applicationContext.xml中<beans>標籤的開頭配置為:
      * spring-framework-3.2.0.RELEASE\docs\spring-framework-reference\html\xsd-config.html,在網頁中找到"40.2.10 the jdbc schma"標題,然後將下面標籤的內容複製到我們的配置檔案中。
    配置內容為:
 
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd"
> </beans>
  * 步驟一:Spring管理內建的連線池
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql:///spring_day03"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </bean>

    * 步驟二:Spring管理模板類
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource"/>
        </bean>

    * 步驟三:編寫測試程式
        @RunWith(SpringJUnit4ClassRunner.class)
        @ContextConfiguration("classpath:applicationContext.xml")
        public class Demo2 {

            @Resource(name="jdbcTemplate")
            private JdbcTemplate jdbcTemplate;

            @Test
            public void run2(){
                jdbcTemplate.update("insert into t_account values (null,?,?)", "測試2",10000);
            }
        }