手写SpringIOC容器如何实现

网友投稿 885 2022-11-05

手写SpringIOC容器如何实现

手写SpringIOC容器如何实现

IOC_自定义对象容器

创建实体类

package com.neu.entity;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;/** * @Author yqq * @Date 2022/05/12 18:23 * @Version 1.0 */@Data@AllArgsConstructor@NoArgsConstructorpublic class Student { private int id; private String name; private Integer age;}

创建Dao接口和实现类

接口

public interface StudentDao { Student findById(int id);}

实现类

public class StudentDaoImpl implements StudentDao { @Override public Student findById(int id) { return new Student(1,"yqq",23); }}

创建配置文件bean.properties

studentDao=com.neu.dao.StudentDaoImplstudentService=com.neu.service.StudentService

创建容器类

该类在类加载时读取配置文件,将配置文件中 配置的对象全部创建并放入容器中。

/** * @Author yqq * @Date 2022/05/12 18:31 * @Version 1.0 * 容器类,负责管理对象,在类加载时读取配置文件并创建对象 */public class Container { static Map map = new HashMap<>(); static { //读取配置文件 InputStream is = Container.class.getClassLoader().getResourceAsStream("bean.properties"); Properties properties = new Properties(); try{ properties.load(is); }catch (Exception e){ e.printStackTrace(); } //遍历配置文件中的所有对象 Enumeration 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

public class StudentService { public Student findStudentById(int id){ //从容器中获取对象 StudentDao studentDao = (StudentDao)Container.getBean("studentDao"); //StudentDao studentDao = new StudentDaoImpl(); return studentDao.findById(1); }}

测试StudentService

public class Test { public static void main(String[] args) { StudentService service = (StudentService)Container.getBean("studentService"); System.out.println(service.findStudentById(1)); }}

StudentService从容器中每次拿到的都是同一个StudentDao对象,节约了资源。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:OpenAI Gym自驾小车模拟环境
下一篇:node.js+express+mongodb 小电商项目实战
相关文章

 发表评论

暂时没有评论,来抢沙发吧~