Spring再接触 IOC DI
2021-07-04 11:07
标签:jdb 引入 path ica 代码 net odi network sys 直接上例子 引入spring以及Junite所需要的jar包 User.java Userservice.java userDAO userDAOimpl beans.xml IOC 即invotion of control 控制反转 本来要由自己写的代码 自己确定的实现 由Spring容器帮我们实现 DI 即依赖注入 即依赖容器帮我们实例化我们实际要实例化的对象 Spring再接触 IOC DI 标签:jdb 引入 path ica 代码 net odi network sys 原文地址:https://www.cnblogs.com/frankzone/p/9612971.htmlpackage 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;
}
}
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;
}
}
package com.bjsxt.dao;
import com.bjsxt.model.User;
public interface UserDAO {
public void save(User user);
}
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!");
}
}
"1.0" encoding="utf-8"?>
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);
}
上一篇:Spring再接触 注入类型
下一篇:Spring再接触 生命周期