Java 簡單模擬 Spring 的 IOC 和 DI
阿新 • • 發佈:2022-03-22
模擬 Spring 的 IOC 和 DI
FakerSpring 類
該類實現了簡單的 spring 物件的控制反轉和依賴注入
package com.ndky.fakeSpring; import com.sun.xml.internal.xsom.impl.scd.Step; import java.lang.reflect.Field; import java.util.Arrays; import java.util.HashMap; import java.util.Locale; /** * @className:FakeSpring * @Description 模擬 Spring 的IOC 和 DI * @Author: ckyfoever * @Date: 2022/3/22 13:37 */ public class FakeSpring { private HashMap<String,Object> beanHaspMap; public FakeSpring() { beanHaspMap = new HashMap<String,Object>(); System.out.println("初始化 fakerSpring"); System.out.println("----------------------"); } // 根據 class 建立物件 public <T> T creatBean(Class<T> beanClass) { T beanObject; try { beanObject = beanClass.newInstance(); Field[] fields= beanClass.getDeclaredFields(); // 迴圈建立物件的引數列表 // 若該引數物件已經建立則注入 for (Field f : fields) { if(beanHaspMap.get(f.getName()) != null) { f.setAccessible(true); f.set(beanObject,beanHaspMap.get(f.getName())); } } } catch (Exception e) { return null; } beanHaspMap.put(beanClass.getSimpleName().toLowerCase(Locale.ROOT),beanObject); return beanObject; } // 根據 class name 獲取物件 public <T> T getBean(String beanName) { return (T) beanHaspMap.get(beanName.toLowerCase(Locale.ROOT)); } }
bean 類
People類
package com.ndky.bean; /** * @className:People * @Description TODO * @Author: ckyfoever * @Date: 2022/3/22 13:41 */ public class People { public int age; public String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "People{" + "age=" + age + ", name='" + name + '\'' + '}'; } }
student 類
package com.ndky.bean; /** * @className:Student * @Description TODO * @Author: ckyfoever * @Date: 2022/3/22 14:16 */ public class Student { public People people; public int grade; public People getPeople() { return people; } public void setPeople(People people) { this.people = people; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } @Override public String toString() { return "Student{" + "people=" + people + ", grade=" + grade + '}'; } }
Main函式
package com.ndky.main;
import com.ndky.bean.People;
import com.ndky.bean.Student;
import com.ndky.fakeSpring.FakeSpring;
/**
* @className:Main
* @Description TODO
* @Author: ckyfoever
* @Date: 2022/3/22 13:42
*/
public class Main {
public static void main(String[] args) {
FakeSpring fakeSpring = new FakeSpring();
People people = fakeSpring.creatBean(People.class);
people.name = "wzp";
people.age = 20;
System.out.println(people);
Student student = fakeSpring.creatBean(Student.class);
System.out.println(student.toString());
}
}
執行結果
/Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home/bin/java -
初始化 fakerSpring
----------------------
People{age=20, name='wzp'}
Student{people=People{age=20, name='wzp'}, grade=0}