1. 程式人生 > >SpringIOC框架詳解

SpringIOC框架詳解

declare puts 文件 load key spa [] tcl for

1、SpringIOC是什麽?

  就是一個用來管理實體類bean的容器

2、創建cppdy.xml文件(模擬springmvc.xml文件)

<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <bean id="user1" class="com.cppdy.UserTest">
        <property key="name" value="cppdy" />
        <property key="sex" value="boy" />
    </bean>
<bean id="user2" class="com.cppdy.UserTest"> <property key="name" value="吹泡泡的魚" /> <property key="sex" value="男" /> </bean> </beans>

3、創建SpringIOCDemo類(模擬SpringIOC獲取bean)

package com.cppdy;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.List; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; class ApplicationResouceReader{ private String url; public ApplicationResouceReader(String url) { this.url=url; } public Object getBean(String id) throws Exception {
//獲取到xml文件 InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(url); SAXReader saxReader = new SAXReader(); Document read = saxReader.read(resourceAsStream); //解析xml,獲取到beanId相同的節點 Element beans = read.getRootElement(); List<Element> beanList = beans.elements(); Element ele; for (int i = 0; i < beanList.size(); i++) { ele=beanList.get(i); if(!ele.attributeValue("id").equals(id)) { continue; } //拿到class全路徑,方便之後反射 String beanClass=ele.attributeValue("class"); //反射出實體類 Class<?> forName = Class.forName(beanClass); Object userInstance = forName.newInstance(); //獲取當前符合id節點的屬性列表 List<Element> attrsList = ele.elements(); //對屬性進行賦值 for (int j = 0; j < attrsList.size(); j++) { String key_zhi = attrsList.get(j).attributeValue("key"); Field declaredField = forName.getDeclaredField(key_zhi); String value_zhi = attrsList.get(j).attributeValue("value"); declaredField.setAccessible(true); declaredField.set(userInstance, value_zhi); } return userInstance; } return null; } } public class SpringIOCDemo { public static void main(String[] args) throws Exception { ApplicationResouceReader arr=new ApplicationResouceReader("cppdy.xml"); UserTest bean = (UserTest) arr.getBean("user1"); System.out.println(bean.toString()); } }

SpringIOC框架詳解