SpringIOC實現原理(自動注入Bean)使用反射

利用Java代碼實現Spring內部IOC實現原理 就三步spring

第一步:解析XMLapi

第二步:獲取每一個Bean的Classapp

第三步:利用反射對Bean的私有屬性賦值this

public class ClassPathXmlApplicationContext {
	
	private String xmlPath;

	public ClassPathXmlApplicationContext(String xmlPath) {
		this.xmlPath = xmlPath;
	}

	public Object getBean(String beanId) throws DocumentException, ClassNotFoundException, NoSuchFieldException,
			SecurityException, IllegalArgumentException, IllegalAccessException, InstantiationException {
		// spring 加載過程 或者spring ioc實現原理
		// 1.讀取xml配置文件
		// 獲取xml解析器
		SAXReader saxReader = new SAXReader();
		// this.getClass().getClassLoader().getResourceAsStream("xmlPath")
		// 獲取當前項目路徑
		Document read = saxReader.read(this.getClass().getClassLoader().getResourceAsStream(xmlPath));
		// 獲取跟節點對象
		Element rootElement = read.getRootElement();
		List<Element> elements = rootElement.elements();
		Object obj = null;
		for (Element sonEle : elements) {
			// 2.獲取到每一個bean配置 獲取class地址
			String sonBeanId = sonEle.attributeValue("id");
			if (!beanId.equals(sonBeanId)) {
				continue;
			}
			String beanClassPath = sonEle.attributeValue("class");
			// 3.拿到class地址 進行反射實例化對象 ,使用反射api 爲私有屬性賦值
			Class<?> forName = Class.forName(beanClassPath);
			obj = forName.newInstance();
			// 拿到成員屬性
			List<Element> sonSoneleme = sonEle.elements();
                        //循環遍歷節點,這裏就是遍歷屬性值
			for (Element element : sonSoneleme) {
                                //屬性名稱
				String name = element.attributeValue("name");
                                //屬性值
				String value = element.attributeValue("value");

				// 使用反射api 爲私有屬性賦值
                                //下面是去拿到屬性名爲name的屬性
				Field declaredField = forName.getDeclaredField(name);
				//容許向私有成員賦值
				declaredField.setAccessible(true);
                                //對當前屬性設置值---向私有屬性賦值
				declaredField.set(obj, value);
			}

		}
		return obj;
	}

	public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException,
			IllegalArgumentException, IllegalAccessException, InstantiationException, DocumentException {
                //設置讀取根路徑下的user.xml,下面有
		ClassPathXmlApplicationContext appLication = new ClassPathXmlApplicationContext("user.xml");
                //獲取user1這個bean
		Object bean = appLication.getBean("user1");
		UserEntity user = (UserEntity) bean;
		System.out.println(user.getUserId() + "----" + user.getUserName());
	}

}

user.xmlcode

<?xml version="1.0" encoding="UTF-8"?>
<beans>
	<bean id="user1" class="com.itmayiedu.entity.UserEntity">
		<property name="userId" value="0001"></property>
		<property name="userName" value="LLL丶Blog"></property>
	</bean>
	<bean id="user2" class="com.itmayiedu.entity.UserEntity">
		<property name="userId" value="0002"></property>
		<property name="userName" value="張三"></property>
	</bean>
</beans>

這裏運行以後控制檯會輸出xml

0001----LLL丶Blog

實現了SpringIOC中的自動注入對象

相關文章
相關標籤/搜索