1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> 6 7 <!--接口注入,UserDAOImpl是实现UserDAO的接口类,主要就是实现数据库的操作,根据不同的数据库类型实现不同的类操作。--> 8 <bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl"> 9 </bean> 10 11 <bean id="userService" class="com.bjsxt.service.UserService"> 12 <!--1、set方法注入,主要用这种方法。--> 13 <property name="userDAO" ref="u" /> 14 <!--2、构造方法注入--> 15 <!-- 16 <constructor-arg> 17 <ref bean="u"/> 18 </constructor-arg> 19 --> 20 </bean> 21 </beans>
UserDAO.java如下:
1 package com.bjsxt.dao; 2 import com.bjsxt.model.User; 3 4 5 public interface UserDAO { 6 public void save(User user); 7 }
UserDAOImpl.java如下:
1 package com.bjsxt.dao.impl; 2 import com.bjsxt.dao.UserDAO; 3 import com.bjsxt.model.User; 4 5 public class UserDAOImpl implements UserDAO { 6 public void save(User user) { 7 //Hibernate 8 //JDBC 9 //XML 10 //NetWork 11 System.out.println("user saved!"); 12 } 13 }
User.java如下:
package com.bjsxt.model; public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
UserService.java如下:
1 package com.bjsxt.service; 2 import com.bjsxt.dao.UserDAO; 3 import com.bjsxt.model.User; 4 5 public class UserService { 6 private UserDAO userDAO; 7 /*用于beans.xml中构造方法的注入使用的; 8 public UserService(UserDAO userDAO){ 9 this.userDAO=userDAO; 10 } 11 */ 12 public void add(User user) { 13 userDAO.save(user); 14 } 15 public UserDAO getUserDAO() { 16 return userDAO; 17 } 18 public void setUserDAO(UserDAO userDAO) { 19 this.userDAO = userDAO; 20 } 21 }
那么如何来使用呢?如下代码是写在测试单元中的:
UserServiceTest.java:
1 package com.bjsxt.service; 2 import org.junit.Test; 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 import com.bjsxt.model.User; 6 7 //Dependency Injection 8 //Inverse of Control 9 public class UserServiceTest { 10 11 @Test 12 public void testAdd() throws Exception { 13 /*读取beans.xml文件ClassPathXmlApplicationContext会把读取的内容放入到bean容器中;*/ 14 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); 15 /*读取注入*/ 16 UserService service = (UserService)ctx.getBean("userService"); 17 User u = new User(); 18 u.setUsername("zhangsan"); 19 u.setPassword("zhangsan"); 20 service.add(u); 21 } 22 }