1. Configure bean in applicationContext. xml
<! -- Configure datasource -->
<Bean id = "dataSource"
Class = "org. apache. commons. dbcp. BasicDataSource">
<Property name = "driverClassName" value = "org. gjt. mm. mysql. Driver"/>
<Property name = "url" value = "jdbc: mysql: // localhost: 3306/test"/>
<Property name = "username" value = ""/>
<Property name = "password" value = ""/>
</Bean>
<! -- Jt bean -->
<Bean id = "jt" class = "org. springframework. jdbc. core. JdbcTemplate">
<Property name = "dataSource" ref = "dataSource"> </property>
</Bean>
<Bean id = "useDao" class = "com. dao. UserDaoImpl">
<Property name = "jdbcTemplete" ref = "jt"> </property>
</Bean>
2, UserDaoImpl. java
Package com. dao;
Import org. springframework. jdbc. core. JdbcTemplate;
Public class UserDaoImpl extends UserDao {
Private JdbcTemplate jdbcTemplete;
Public void setJdbcTemplete (JdbcTemplate jdbcTemplete ){
This. jdbcTemplete = jdbcTemplete;
}
Public void addData (){
String SQL = "insert into m_s (id, name) values (\" 6 \ ", \" @-H \")";
JdbcTemplete. update (SQL );
}
Public int delete (int id ){
String SQL = "delete from m_s where id =? ";
Return jdbcTemplete. update (SQL, new Object [] {id });
}
}
Get bean tool class; GetBeanUtil. java
Package util;
Import org. springframework. context. ApplicationContext;
Import org. springframework. context. support. ClassPathXmlApplicationContext;
Public class GetBeanUtil {
Public static ApplicationContext ac = new ClassPathXmlApplicationContext ("applicationContext. xml ");
Public static Object getBean (String name ){
Return ac. getBean (name );
}
}
Test
UserDaoImpl userdao = (UserDaoImpl) ac. getBean ("useDao ");
Userdao. addData ();
Userdao. delete (6 );