尚学堂
包: spring.jar commoms-logging.jar [2.5.6在dist 和 lib 里]
1。 userDAO.java
package com.bjsxt.dao; import com.bjsxt.model.User; public interface UserDAO { public void save(User user); }
2。 UserDAOImpl.java
package com.bjsxt.dao.impl; import com.bjsxt.dao.UserDAO; import com.bjsxt.model.User; public class UserDAOImpl implements UserDAO { public void save(User user) { //Hibernate //JDBC //XML //NetWork System.out.println("user saved!"); } }
3。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; } }
4.UserService.java
package com.bjsxt.service; import com.bjsxt.dao.UserDAO; import com.bjsxt.model.User; public class UserService { //未使用new 控制反转(IOC),使用了beans.xml new 出来了 private UserDAO userDAO; public void add(User user) { userDAO.save(user); } //Getter and Setter
public UserDAO getUserDAO() { return userDAO; } public void setUserDAO(UserDAO userDAO) { this.userDAO = userDAO; } }
5。 beans.xml
<?xml version="1.0" encoding="UTF-8"?> <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"> <!-- 相当于一个new UserDAOImpl() --> <bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl"> </bean> <!-- 相当于一个new UserService() --> <bean id="userService" class="com.bjsxt.service.UserService"> <property name="userDAO" ref="u" /> </bean> </beans>