Hello Spring(3)ConnectionUtility

ConnectionUtility.java

 1 package test;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 
 6 public class ConnectionUtility {
 7     
 8     private String userName;
 9     private String password;
10     private String dbUrl;
11     private String dbDriver;
12     
13     public Connection getConnection(){
14         
15         try {
16             Class.forName(dbDriver);
17             return DriverManager.getConnection(dbUrl, userName, password);
18         } catch (Exception e) {
19             // TODO Auto-generated catch block
20             e.printStackTrace();
21         }
22         
23         return null ;
24         
25     }
26     
27     
28     public String getUserName() {
29         return userName;
30     }
31     public void setUserName(String userName) {
32         this.userName = userName;
33     }
34     public String getPassword() {
35         return password;
36     }
37     public void setPassword(String password) {
38         this.password = password;
39     }
40     public String getDbUrl() {
41         return dbUrl;
42     }
43     public void setDbUrl(String dbUrl) {
44         this.dbUrl = dbUrl;
45     }
46     public String getDbDriver() {
47         return dbDriver;
48     }
49     public void setDbDriver(String dbDriver) {
50         this.dbDriver = dbDriver;
51     }
52     
53     
54 
55 }

 beans.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE beans PUBLIC "" "http://www.springframework.org/dtd/spring-beans.dtd" >
 3 <beans>
 4 
 5     <bean id="conn" class="test.ConnectionUtility">
 6         <property name="userName" value="root"></property>
 7         <property name="password" value="root"></property>
 8         <property name="dbUrl" value="jdbc:mysql://192.168.1.136:3306/db_epolice"></property>
 9         <property name="dbDriver" value="com.mysql.jdbc.Driver"></property>
10     </bean>
11 
12 </beans>

 

Tester.java

 1 package test;
 2 
 3 import java.sql.Connection;
 4 
 5 import org.springframework.beans.factory.BeanFactory;
 6 import org.springframework.beans.factory.xml.XmlBeanFactory;
 7 import org.springframework.core.io.ClassPathResource;
 8 import org.springframework.core.io.Resource;
 9 
10 @SuppressWarnings("deprecation")
11 public class Tester {
12     
13     public static void main( String[] args){
14         
15         Resource r = new ClassPathResource("beans.xml");
16         BeanFactory factory = new XmlBeanFactory(r);
17         
18         ConnectionUtility util = (ConnectionUtility) factory.getBean("connectionUtility");
19         Connection conn = util.getConnection();
20         
21         System.out.println( conn );
22         
23     }
24 
25 }

 

result

 

posted on 2013-03-26 15:50  Livon  阅读(204)  评论(0编辑  收藏  举报

导航