日期:2014-05-16 浏览次数:20529 次
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/databaseName" /> <property name="username" value="root" /> <property name="password" value="1234"/> </bean> <bean id="dbHome" class="com.DBHome"> <property name="dataSource" ref="dataSource"></property> </bean> </beans>
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.*; import org.springframework.core.io.*; public class InitServlet extends HttpServlet { public static Resource res = null; public static BeanFactory factory = null; public InitServlet() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } @SuppressWarnings("deprecation") public void init() throws ServletException { if(res==null) res = new ClassPathResource("/com/beans.xml"); if(factory==null) factory = new XmlBeanFactory(res); } }
import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.springframework.jdbc.datasource.DriverManagerDataSource; public class DBHome { public DriverManagerDataSource database = null; public DBHome() { } public DBHome(DriverManagerDataSource database) { System.out.println("++++++++++++"); this.setDataSource(database); } public void setDataSource(DriverManagerDataSource database){ //注意这个必须要写这个set方法,这个方法起名是有要求的:set+在beans里面database映射到DBHome里面的名字(首字母要变大写),也就是setDataSource。这样写,beans会自动找到这个方法,然后给DriverManagerDataSource database赋值。 this.database = database; } public void test(){ Connection conn=null; try { conn =database.getConnection(); Statement s =conn.createStatement(); ResultSet res =s.executeQuery("select * from userTable"); while(res.next()){ System.out.println(res.getString(2)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class UserServlet extends HttpServlet { public DBHome home = (DBHome)InitServlet.factory.getBean("dbHome");//从beans里面取生成的对象。 public UserServlet() { super(); } public void destroy() { super.destroy(); // Just puts "destro