文件结构
user.Bean.java
1 package user; 2 3 public class Bean { 4 5 private String name; 6 private String passwork; 7 8 public String getName() { 9 return name; 10 } 11 public void setName(String name) { 12 this.name = name; 13 } 14 public String getPasswork() { 15 return passwork; 16 } 17 public void setPasswork(String passwork) { 18 this.passwork = passwork; 19 } 20 21 22 23 }
user.Dao.java
1 package user; 2 3 public interface Dao { 4 5 public void register( Bean bean ); 6 7 }
user.DaoImpl.java
1 package user; 2 3 import java.sql.Connection; 4 5 import test.ConnectionUtility; 6 7 public class DaoImpl implements Dao { 8 9 private ConnectionUtility connectionUtility; 10 11 12 13 public ConnectionUtility getConnectionUtility() { 14 return connectionUtility; 15 } 16 17 18 19 public void setConnectionUtility(ConnectionUtility connectionUtility) { 20 this.connectionUtility = connectionUtility; 21 } 22 23 24 25 public void register( Bean bean ){ 26 27 Connection conn = connectionUtility.getConnection(); 28 System.out.println(conn); 29 System.out.println("哈哈,天空真蓝,世界平静了!"); 30 31 } 32 33 }
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="connectionUtility" class="test.ConnectionUtility"> 6 <property name="userName" value="Livon"></property> 7 <property name="password" value="Livon_2012"></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 <bean id="userDao" class="user.DaoImpl"> 13 <property name="connectionUtility" ref="connectionUtility"></property> 14 </bean> 15 16 </beans>
test.Tester.java
1 package test; 2 3 import org.springframework.beans.factory.BeanFactory; 4 import org.springframework.beans.factory.xml.XmlBeanFactory; 5 import org.springframework.core.io.ClassPathResource; 6 import org.springframework.core.io.Resource; 7 8 import user.Dao; 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 user.Dao dao = (Dao) factory.getBean("userDao"); 19 dao.register( new user.Bean()); 20 21 } 22 23 }
result