1,applicationContext.xml配置bean
<!-- 配置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}); } } 获取bean工具类;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); } } 测试 UserDaoImpl userdao = (UserDaoImpl) ac.getBean("useDao"); userdao.addData(); userdao.delete(6);