近日,在研究 Spring ,看到模板方法有这样一段代码:

一时没有搞明白,经过仔细研究 发现可以用内部类来实现,而Spring
时用接口来实现的。以下时我写的内部类的实现方法:
mysql:
create database school;

use school;

create table student
(
stu_id int not null primary key,
stu_name varchar(20) not null,
stu_age int
);

select * from student;
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql:///school</value>
</property>
<property name="username">
<value>root</value>
</property>
</bean>
</beans>
DriverManager.java
package test;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class DriverManager ...{

public DataSource getDataSource() ...{
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");

javax.sql.DataSource dataSource = (DataSource) context
.getBean("dataSource");

return dataSource;

}


public static void main(String[] args) ...{
javax.sql.DataSource d = new DriverManager().getDataSource();

System.out.println(d);
}
}
JdbcTemplate.java
package test;

import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.sql.DataSource;


public class JdbcTemplate ...{
private DataSource dataSource;


public JdbcTemplate(DataSource dataSource) ...{
super();
this.dataSource = dataSource;
}


static class PreparedStatementSetter ...{
protected java.sql.PreparedStatement pstmt;


public void setValues(PreparedStatement pstmt) throws SQLException ...{
this.pstmt = pstmt;
}
}


public void insert(String sql, PreparedStatementSetter pss) ...{

try ...{
java.sql.Connection con = dataSource.getConnection();
java.sql.PreparedStatement pstmt = con.prepareStatement(sql);


try ...{
pss.setValues(pstmt);

} catch (Exception e) ...{
// TODO 自动生成 catch 块
e.printStackTrace();
}
pstmt.executeUpdate();

pstmt.close();
con.close();


} catch (Exception e) ...{
// TODO 自动生成 catch 块
e.printStackTrace();
}

}


public static void main(String[] args) ...{

DriverManager d = new DriverManager();
javax.sql.DataSource dataSource = d.getDataSource();

JdbcTemplate template = new JdbcTemplate(dataSource);

String sql = "insert into student values (?,?,?)";


template.insert(sql, new PreparedStatementSetter() ...{

public void setValues(PreparedStatement pstmt) ...{

try ...{
pstmt.setInt(1, 1112);
pstmt.setString(2, "aaaaaaaaaa");
pstmt.setInt(3, 19);

} catch (Exception e) ...{
// TODO 自动生成 catch 块
e.printStackTrace();
}

}
});
}

}
