下面就是一个添加用户的小
例子,详细描写了IoC配置步骤,遵从MVC框架,spring的起步,关键是对beans.xml的
理解,其实还是反射、注入、切面这些高级编程手段的使用。
1、创建实体类
class="java">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;
}
}
2、创建数据库与Dao
接口并实现之
public interface UserDAO {
public void save(User user);
}
public class UserDAOImpl implements UserDAO {
public void save(User user) {
System.out.println("user saved!");
}
}
3、创建service方法
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;
}
}
4、配置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">
<bean id="nameonyourdemand" class="com.jt.dao.impl.UserDAOImpl">
</bean>
<bean id="userService" class="com.jt.service.UserService">
<property name="userDAO" ref="nameonyourdemand"/>
</bean>
</beans>
5、JUnit测试
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
//Dependency Injection
//Inverse of Control
public class UserServiceTest {
@Test
public void testAdd() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
UserService service = (UserService)ctx.getBean("userService");
User user = new User();
user.setUsername("zhangsan");
user.setPassword("zhangsan");
service.add(user);
}
}