直接上例子
引入spring以及Junite所需要的jar包
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
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; } }
userDAO
package com.bjsxt.dao; import com.bjsxt.model.User; public interface UserDAO { public void save(User user); }
userDAOimpl
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!"); } }
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="u" class="com.bjsxt.dao.impl.UserDAOImpl"> </bean> <bean id="userService" class="com.bjsxt.service.UserService"> <property name="userDAO" ref="u"/> </bean> </beans>
public class UserServiceTest { @Test public void testAdd() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); //读取到配置文件 UserService service = (UserService)ctx.getBean("userService"); //Spring根据配置文件将UserDAO的实现注入到userdao 然后将userdao注入到userservice User u = new User(); u.setUsername("zhangsan"); u.setPassword("zhangsan"); service.add(u); }
IOC 即invotion of control 控制反转 本来要由自己写的代码 自己确定的实现 由Spring容器帮我们实现
DI 即依赖注入 即依赖容器帮我们实例化我们实际要实例化的对象
原文地址:https://www.cnblogs.com/frankzone/p/9612971.html
时间: 2024-11-09 01:39:59