Sping--IOC概念
1. 新建项目, 引入spring包(sping, common-annotation, common-logging包), 还有junit包.
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; } }
UserDAO.java:
package com.bjsxt.dao; import com.bjsxt.model.User; public interface UserDAO { public void save(User user); }
UserDAOImpl.java:
package com.bjsxt.dao; import com.bjsxt.model.User; public interface UserDAO { public void save(User user); }
UserService.java:
package com.bjsxt.service; import com.bjsxt.dao.UserDAO; import com.bjsxt.model.User; public class UserService { private UserDAO userDAO; public void add(User user) { userDAO.save(user); } public UserDAO getUserDAO() { return userDAO; } public void setUserDAO(UserDAO userDAO) { this.userDAO = userDAO; } }
依赖注入bean.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"> <bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl"> </bean> <bean id="userService" class="com.bjsxt.service.UserService"> <property name="userDAO" ref="u" /> </bean> </beans>