第一步:
spring配置applicationContext.xml文件,放在src下面:
<?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.springframework.jdbc.datasource.DriverManagerDataSource" destroy-method="close"> // <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> // <property name="url" value="jdbc:oracle:thin:@localhost:1521:db10g"/> <property name="url" value="jdbc:mysql://localhost:3306/iminer"/> <property name="username" value="test"/> <property name="password" value="pwd"/> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref bean="dataSource" /> </property> </bean> <bean id="jdbcUtil" class="com.maggie.util.JdbcUtil"> <property name="jdbcTemplate"> <ref bean="jdbcTemplate" /> </property> </bean> </beans>
----------------------------------------------------------------------------------------
第二步:com.maggie.util.JdbcUtil.java 类文件:
<?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.springframework.jdbc.datasource.DriverManagerDataSource" destroy-method="close"> // <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> // <property name="url" value="jdbc:oracle:thin:@localhost:1521:db10g"/> <property name="url" value="jdbc:mysql://localhost:3306/iminer"/> <property name="username" value="test"/> <property name="password" value="pwd"/> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref bean="dataSource" /> </property> </bean> <bean id="jdbcUtil" class="com.maggie.util.JdbcUtil"> <property name="jdbcTemplate"> <ref bean="jdbcTemplate" /> </property> </bean> </beans>
----------------------------------------------------------------------------------------
第三步:测试类:
package com.maggie.test; import java.util.Map; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import com.maggie.util.JdbcUtil; public class Test{ private JdbcUtil jdbc; public Test() { ClassPathResource res = new ClassPathResource("applicationContext.xml"); XmlBeanFactory factory = new XmlBeanFactory(res); jdbc = (JdbcUtil) factory.getBean("jdbcUtil"); } public String getUsernameById(String id) { Map dataName = jdbc.getJdbcTemplate().queryForMap( "select t.username from tablename t where t.id=?", new Object[] { id }); return (String) dataName.get("username"); } public static void main(String[] args) { Test test = new Test(); String id = "1"; String username = test.getUsernameById(id); System.out.println("*************** username = "+username); } }
时间: 2024-12-08 10:33:48