手写springIoc框架

springIoc的底层实现原理

1.读取bean的XML配置文件

2.使用beanId查找bean配置,并获取配置文件中class地址。

3.使用Java反射技术实例化对象

4.获取属性配置,使用反射技术进行赋值

使用人家spring框架读取对象

创建实体


package com.itmayiedu.service;

public class UserEntity {
	private String userId;
	private String userName;

	 public UserEntity(){
		 System.out.println("无参构造函数....");
	 }

	public String getUserId() {

		return userId;
	}

	public void setUserId(String userId) {

		this.userId = userId;
	}

	public String getUserName() {

		return userName;
	}

	public void setUserName(String userName) {

		this.userName = userName;
	}

}

创建spring的配置文件 application.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
     http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/tx
     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<bean id="user1" class="com.itmayiedu.service.UserEntity">
		<property name="userId" value="0002"></property>
		<property name="userName" value="张三"></property>
	</bean>
	<bean id="user2" class="com.itmayiedu.service.UserEntity">
		<property name="userId" value="0002"></property>
		<property name="userName" value="张三"></property>
	</bean>
</beans> 

读取配置文件

package com.itmayiedu.service;

import org.springframework.context.support.ClassPathXmlApplicationContext;

@SuppressWarnings("resource")
public class Main {

	public static void main(String[] args) {
        //1.读取springxml配置
		ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		//2.获取bean对象
		UserEntity userEntity = (UserEntity) classPathXmlApplicationContext.getBean("user1");
		System.out.println(userEntity.getUserId()+"----"+userEntity.getUserName());
	}

}

自己手写springIoc框架

编写配置文件user.xml

<?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="张三"></property>
	</bean>
	<bean id="user2" class="com.itmayiedu.entity.UserEntity">
		<property name="userId" value="0002"></property>
		<property name="userName" value="张三"></property>
	</bean>
</beans>

编写读取user.xml的方法


package com.itmayiedu.classFrorm;

import java.lang.reflect.Field;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.itmayiedu.entity.UserEntity;

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 为私有属性赋值
				Field declaredField = forName.getDeclaredField(name);
				//运行往私有成员赋值
				declaredField.setAccessible(true);
				declaredField.set(obj, value);
			}

		}
		// 3.拿到class地址 进行反射实例化对象 ,使用反射api 为私有属性赋值
		return obj;
	}

	public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException,
			IllegalArgumentException, IllegalAccessException, InstantiationException, DocumentException {
		ClassPathXmlApplicationContext appLication = new ClassPathXmlApplicationContext("user.xml");
		Object bean = appLication.getBean("user1");
		UserEntity user = (UserEntity) bean;
		System.out.println(user.getUserId() + "----" + user.getUserName());
	}

}

创建对应的user实体省略了

原文地址:https://www.cnblogs.com/wang66a/p/12069290.html

时间: 2024-08-05 23:37:18

手写springIoc框架的相关文章

(二)springMvc原理和手写springMvc框架

我们从两个方面了解springmvc执行原理,首先我们去熟悉springmvc执行的过程,然后知道原理后通过手写springmvc去深入了解代码中执行过程. (一)SpringMVC流程图 (二)SpringMVC流程 1.  用户发送请求至前端控制器DispatcherServlet. 2.  DispatcherServlet收到请求调用HandlerMapping处理器映射器. 3.  处理器映射器找到具体的处理器(可以根据xml配置.注解进行查找),生成处理器对象及处理器拦截器(如果有则

手写SpringMVC 框架

手写SpringMVC框架 细嗅蔷薇 心有猛虎 背景:Spring 想必大家都听说过,可能现在更多流行的是Spring Boot 和Spring Cloud 框架:但是SpringMVC 作为一款实现了MVC 设计模式的web (表现层) 层框架,其高开发效率和高性能也是现在很多公司仍在采用的框架:除此之外,Spring 源码大师级的代码规范和设计思想都十分值得学习:退一步说,Spring Boot 框架底层也有很多Spring 的东西,而且面试的时候还会经常被问到SpringMVC 原理,一般

手写Spring框架,加深对Spring工作机制的理解!

在我们的日常工作中,经常会用到Spring.Spring Boot.Spring Cloud.Struts.Mybatis.Hibernate等开源框架,有了这些框架的诞生,平时的开发工作量也是变得越来越轻松,我们用 Spring Boot 分分钟可以新建一个Web项目. 记得自己刚开始工作的时候还是在用Servlet写Web项目,自己写数据库连接池,用原生JDBC操作数据库,好了不发散了.回到这篇文章的主题,今天通过手写Spring框架,帮大家深入了解一下Spring的工作机制,文中涉及的代码

手写集合框架LinkedList实现篇

<手写集合框架>LinkedList篇 嘿嘿嘿,拖延症犯了,这几天不怎么想写代码,所以趁没事干就写写了.进入正文 还是老套路嘻嘻嘻,因为我之前写了那个准备篇,对node已经描述的从差不多了,所以我就不过多描述了. 直接贴完代码强行解释一波 一.定义接口 public interface newList<T> { //定义泛型,因为Object可以存储任意类型,有时候我们需要 //用泛型 代替Object public void add(Object object); //集合的添加

纯手写SpringBoot框架之注解方式启动SpringMVC容器

使用Java语言创建Tomcat容器,并且通过Tomcat执行Servlet,接下来,将会使用Java语言在SpringBoot创建内置Tomcat,使用注解方式启动SpringMVC容器. 代码实现.1.pom.xml文件,需要依赖的jar包. <dependencies> <!--Java语言操作Tomcat--> <dependency> <groupId>org.apache.tomcat.embed</groupId> <arti

尝试手写orm框架

前言: 在使用各种的orm框架的过程中,菜鸟的我始终没有搞懂底层实现技术,最近刚好没事找了些视频和资料了解一点皮毛,想记录下,大家勿喷. 所谓的ORM(Object Relational Mapping) 对象关系映射 官方解释是通过使用描述对象和数据库之间映射的元数据,将面向对象程序的对象自动持久化到关系数据库中. 个人理解就是一个数据库访问的帮助类,可以让我们不用手写sql,就完成数据库的访问 使用的技术: 泛型.反射.特性.扩展 摸索步骤: step1 新建项目,建几个类库,大家熟悉的三层

纯手写springIOC

大家好啊- 那么今天来带大家写一下spring的ioc. 其实也很简单,首先我们明白两点,java解析xml和java的反射机制,因为ioc就是主要是基于这两个来实现,今天只是简单的来大家实现下. 废话不多说直接上代码. 1.首先加入maven依赖我们这里用到的xml解析是dem4j,先看下项目结构吧. 2.导入maven依赖 1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns=&qu

大数据学习之手写MR框架(WordCount程序开发)08

简介:这里先手写一个MR程序,大致实现一个单词计数程序.帮助后面学习MapReduce组件. 1:先自定义一个Mapper接口 package it.dawn.HDFSPra.HandWritingMR; /** * @author Dawn * @date 2019年4月30日23:28:00 * @version 1.0 * * 思路? * 接口设计 */ public interface Mapper { //通用方法 public void map(String line,Context

手写web框架之加载配置项目

一  定义框架配置项 在项目的src/main/resources目录下创建一个名为smart.propertiesd的文件,文件的内容如下: 1 smart.framework.jdbc.driver=com.mysql.jdbc.Driver 2 smart.framework.jdbc.url=jdbc:mysql://localhost:3306/jack 3 smart.framework.jdbc.username=root 4 smart.framework.jdbc.passwo