什麼是SpringIOC
spring ioc指的是控制反轉,IOC容器負責實例化、定位、配置應用程序中的對象及建立這些對象間的依賴。交由Spring來管理這些,實現解耦
SpringIOC原理
使用反射機制+XML技術
手寫Spring專題 XML方式注入bean
/** * 手寫Spring專題 XML方式注入bean * * */ public class ClassPathXmlApplicationContext { // xml路徑地址 private String xmlPath;
public ClassPathXmlApplicationContext(String xmlPath) { this.xmlPath = xmlPath; }
public Object getBean(String beanId) throws Exception { // 1. 讀取配置文件 List<Element> elements = readerXml(); if (elements == null) { throw new Exception("該配置文件沒有子元素"); } // 2. 使用beanId查找對應的class地址 String beanClass = findXmlByIDClass(elements, beanId); if (StringUtils.isEmpty(beanClass)) { throw new Exception("未找到對應的class地址"); } // 3. 使用反射機制初始化,對象 Class<?> forName = Class.forName(beanClass); return forName.newInstance(); }
// 讀取配置文件信息 public List<Element> readerXml() throws DocumentException { SAXReader saxReader = new SAXReader(); if (StringUtils.isEmpty(xmlPath)) { new Exception("xml路徑爲空..."); } Document read = saxReader.read(getClassXmlInputStream(xmlPath)); // 獲取根節點信息 Element rootElement = read.getRootElement(); // 獲取子節點 List<Element> elements = rootElement.elements(); if (elements == null || elements.isEmpty()) { return null; } return elements; }
// 使用beanid查找該Class地址 public String findXmlByIDClass(List<Element> elements, String beanId) throws Exception { for (Element element : elements) { // 讀取節點上是否有value String beanIdValue = element.attributeValue("id"); if (beanIdValue == null) { throw new Exception("使用該beanId爲查找到元素"); } if (!beanIdValue.equals(beanId)) { continue; } // 獲取Class地址屬性 String classPath = element.attributeValue("class"); if (!StringUtils.isEmpty(classPath)) { return classPath; } } return null; }
// 讀取xml配置文件 public InputStream getClassXmlInputStream(String xmlPath) { InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(xmlPath); return resourceAsStream; }
} |
測試:
public class Test002 { public static void main(String[] args) throws Exception { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); User user = (User) applicationContext.getBean("user"); System.out.println(user); }
} |