JAVA全系列 教程
3762个小节阅读:7090.9k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
接下来我们通过一段代码模拟IOC思想。创建一个集合容器,先将对象创建出来放到容器中,需要使用对象时,只需要从容器中获取对象即可,而不需要重新创建,此时容器就是对象的管理者。
创建实体类
xxxxxxxxxx
public class Student {
private int id;
private String name;
private String address;
// 省略getter/setter/构造方法/tostring
}
创建Dao接口和实现类
xxxxxxxxxx
public interface StudentDao {
// 根据id查询学生
Student findById(int id);
}
public class StudentDaoImpl implements StudentDao {
@Override
public Student findById(int id) {
// 模拟从数据库查找出学生
return new Student(1,"百战程序员","北京");
}
}
public class StudentDaoImpl2 implements StudentDao {
@Override
public Student findById(int id) {
// 模拟从数据库查找出学生
System.out.println("新方法!!!");
return new Student(1,"百战程序员","北京");
}
}
创建配置文件bean.properties,该文件中定义管理的对象
xxxxxxxxxx
studentDao=com.itbaizhan.dao.impl.StudentDaoImpl
创建容器管理类,该类在类加载时读取配置文件,将配置文件中配置的对象全部创建并放入容器中。
xxxxxxxxxx
public class Container {
static Map<String,Object> map = new HashMap<>();
static {
// 读取配置文件
InputStream is = Container.class.getClassLoader().getResourceAsStream("bean.properties");
Properties properties = new Properties();
try {
properties.load(is);
} catch (IOException e) {
throw new RuntimeException(e);
}
// 遍历配置文件的所有配置信息
Enumeration<Object> keys = properties.keys();
while (keys.hasMoreElements()){
String key = keys.nextElement().toString();
String value = properties.getProperty(key);
try {
// 创建对象,将对象放入集合
Object o = Class.forName(value).newInstance();
map.put(key,o);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 从容器中获取对象
public static Object getBean(String key){
return map.get(key);
}
}
创建Dao对象的调用者StudentService
xxxxxxxxxx
public class StudentService {
public Student findStudentById(int id){
StudentDao studentDao = (StudentDao) Container.getBean("studentDao");
System.out.println(studentDao.hashCode());
return studentDao.findById(id);
}
}
测试StudentService
xxxxxxxxxx
public class Test {
public static void main(String[] args) {
StudentService studentService = new StudentService();
System.out.println(studentService.findStudentById(1));
System.out.println(studentService.findStudentById(1));
}
}
测试结果:
StudentService从容器中每次拿到的都是同一个StudentDao对象,节约了资源。
如果想使用StudentDaoImpl2对象,只需要修改bean.properties的内容为
xxxxxxxxxx
studentDao=com.itbaizhan.dao.StudentDaoImpl2
即可,无需修改Java源码。