当前位置: 首页 > news >正文

手写Spring

简单实现Spring基于注解配置

 

ComponentScan

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ComponentScan {String value() default "";
}

相当于component-scan 

HspSpringConfig

@ComponentScan(value = "spring.write.component")
public class HspSpringConfig {
}

替代bean.xml文件,添加@ComponentScan,获得扫描的包

AppMain

public class AppMain {public static void main(String[] args) {HspApplicationContext ioc = new HspApplicationContext(HspSpringConfig.class);Object userDao = ioc.getBean("userDao");System.out.println(userDao);}
}

HspApplicationContext

public class HspApplicationContext {private Class configClass;private final ConcurrentHashMap<String, Object> ioc = new ConcurrentHashMap<>();public HspApplicationContext(Class configClass) {//1、获得扫描包路径//得到config文件的.class类型this.configClass = configClass;//反射得到ComponentScan注解ComponentScan componentScan =(ComponentScan)configClass.getDeclaredAnnotation(ComponentScan.class);//获取注解的value就是扫描的包路径String path = componentScan.value();System.out.println(path);//spring.write.component//2、得到包下的所有.class//得到类的加载器,获取实际目录下的(out),ClassLoader classLoader = ClassLoader.getSystemClassLoader();//URL必须按照斜杠/来写//path = spring.write.componentpath = path.replace(".","/");URL resource = classLoader.getResource(path);System.out.println(resource);//file:/D:/Atest/spring/out/production/spring/spring/write/component//对路径下的文件进行遍历File file = new File(resource.getFile());if(file.isDirectory()) {File[] files = file.listFiles();for (File f : files) {//只处理.class文件(java文件)String fileAbsolutePath = f.getAbsolutePath();if(fileAbsolutePath.endsWith(".class")) {System.out.println(fileAbsolutePath);//D:\Atest\spring\out\production\spring\spring\write\component\UserDao.class//前面已经有了path,还需要具体的类名进行反射,放入容器String className = fileAbsolutePath.substring(fileAbsolutePath.lastIndexOf("\\") + 1, fileAbsolutePath.indexOf(".class"));String classFullName = path.replace("/", ".") + "." + className;//判断该类是不是需要注入到容器,有无注解try {Class<?> aClass = classLoader.loadClass(classFullName);//判断该类的实例是否有注解if(aClass.isAnnotationPresent(Component.class) ||aClass.isAnnotationPresent(Controller.class) ||aClass.isAnnotationPresent(Service.class) ||aClass.isAnnotationPresent(Repository.class)) {//查看是否指定了idif(aClass.isAnnotationPresent(Component.class)) {//只演示了ComponentComponent component = aClass.getDeclaredAnnotation(Component.class);String id = component.value();if(! "".endsWith(id)) {className = id;}}//放入容器Class<?> clazz = Class.forName(classFullName);Object instance = clazz.newInstance();//类名首字母小写存入,springframework下的工具类ioc.put(StringUtils.uncapitalize(className),instance);}} catch (Exception e) {e.printStackTrace();}}}}}public Object getBean(String name) {return ioc.get(name);}
}

Spring整体架构分析

没有加@Scope(value="prototype")就是单例
ioc.getBean("name"),先到BeanDefinition Map获取,未找到异常处理,
如果是单例(single)就从单例Bean Map获取
如果是多例(prototype)就创建bean对象并返回(到BeanDefinition Map中,得到Bean的clazz对象,使用反射,创建bean返回)

1、实现扫描包,得到bean的class对象

Spring基于注解配置已经写过

HspApplicationContext

public class HspApplicationContext {private Class configClass;public HspApplicationContext(Class configClass) {this.configClass = configClass;ComponentScan componentScan =(ComponentScan) this.configClass.getDeclaredAnnotation(ComponentScan.class);String path = componentScan.value();System.out.println(path);//com.spring.componentClassLoader classLoader =HspApplicationContext.class.getClassLoader();path = path.replace(".", "/");System.out.println(path);//com/spring/componentURL resource =classLoader.getResource(path);File file = new File(resource.getFile());if(file.isDirectory()) {File[] files = file.listFiles();for (File f : files) {String fileAbsolutePath = f.getAbsolutePath();if(fileAbsolutePath.endsWith(".class")) {String className = fileAbsolutePath.substring(fileAbsolutePath.lastIndexOf("\\") + 1, fileAbsolutePath.indexOf(".class"));String classFullName = path.replace("/", ".") + "." + className;try {Class<?> clazz = classLoader.loadClass(classFullName);if(clazz.isAnnotationPresent(Component.class)) {System.out.println("是Spring bean【class对象】= " + clazz + " 【类名】 = " + className);} else {System.out.println("不是Spring bean【class对象】= " + clazz + " 【类名】 = " + className);}} catch (Exception e) {e.printStackTrace();}}}}}
}

2、扫描bean信息,封装到BeanDefinition对象并放入Map

增加@Scope注解来判断单例(single)或者多例(prototype)

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Scope {String value() default "";
}

BeanDefinition用于封装/记录Bean信息
1、单例/多例
2、多例需要动态生成,存放Bean对应的Class对象,反射生成

public class BeanDefinition {private String scope;private Class clazz;public String getScope() {return scope;}public void setScope(String scope) {this.scope = scope;}public Class getClazz() {return clazz;}public void setClazz(Class clazz) {this.clazz = clazz;}@Overridepublic String toString() {return "BeanDefinition{" +"scope='" + scope + '\'' +", clazz=" + clazz +'}';}
}

HspApplicationContext

private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap =new ConcurrentHashMap<>();
//单例对象类型不确定,用Object
private ConcurrentHashMap<String, Object> singletonObejcts =new ConcurrentHashMap<>();

如果有@Component,就放入beanDefinitionMap中

可以将1、2步写成一个方法,在构造器里调用

3、初始化bean单例池并完成getBean、createBean方法

public class HspApplicationContext {private Class configClass;private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap =new ConcurrentHashMap<>();//单例对象类型不确定,用Objectprivate ConcurrentHashMap<String, Object> singletonObejcts =new ConcurrentHashMap<>();public HspApplicationContext(Class configClass) {//完成扫描指定包beanDefinitionScan(configClass);//遍历所有的beanDefinition对象Enumeration<String> keys = beanDefinitionMap.keys();while(keys.hasMoreElements()) {String beanName = keys.nextElement();BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);if("singleton".equalsIgnoreCase(beanDefinition.getScope())) {Object bean = createBean(beanDefinition);singletonObejcts.put(beanName,bean);}}System.out.println("singletonObejcts单例池=" + singletonObejcts);System.out.println("beanDefinitionMap=" + beanDefinitionMap);}public void beanDefinitionScan(Class configClass) {}public Object createBean(BeanDefinition beanDefinition) {Class clazz = beanDefinition.getClazz();try {Object instance = clazz.getDeclaredConstructor().newInstance();return instance;} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();} catch (NoSuchMethodException e) {e.printStackTrace();}return null;}public Object getBean(String name) {//判断beanName是否存在if(beanDefinitionMap.containsKey(name)) {BeanDefinition beanDefinition = beanDefinitionMap.get(name);if("singleton".equalsIgnoreCase(beanDefinition.getScope())) {return singletonObejcts.get(name);} else {return createBean(beanDefinition);}} else {throw new NullPointerException("没有该Bean");}}
}

4、依赖注入

增加@Autowired注解,这里只用名字来进行匹配

 

    public Object createBean(BeanDefinition beanDefinition) {Class clazz = beanDefinition.getClazz();try {Object instance = clazz.getDeclaredConstructor().newInstance();//遍历所有字段,for(Field field : clazz.getDeclaredFields()) {//是否有Autowiredif(field.isAnnotationPresent(Autowired.class)) {String name = field.getName();//通过getBean获取要组装的对象Object bean = getBean(name);//进行组装,private需要暴破field.setAccessible(true);field.set(instance,bean);//将 bean 赋值给 instance 的 field}}return instance;} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();} catch (NoSuchMethodException e) {e.printStackTrace();}return null;}

5、bean后置处理器实现

原生Spring接口InitializingBean(初始化),自己实现这个接口,完成初始化方法
接口中有afterPropertiesSet()方法,在Bean的setter方法执行完毕后,被spring容器调用,就是初始化方法

public interface InitializingBean {void afterPropertiesSet() throws Exception;
}

应用:选择MonsterService来实现这个接口

@Component("monsterService")
@Scope(value = "property")
public class MonsterService implements InitializingBean {@Autowiredprivate MonsterDao monsterDao;public void m1() {monsterDao.hi();}@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("monsterService初始化方法被调用");}
}

在创建好Bean实例后,判断是否需要初始化
容器中常用的一个方法是:根据该类是否实现了某个接口,来判断是否要执行某个业务(接口编程)

在HspApplicationContext的createBean返回instance之前加上判断是否是这个接口的子类型,是的话就执行初始化方法

判断如果返回为null,不变化
加上beanName

public Object createBean(String beanName, BeanDefinition beanDefinition) {Class clazz = beanDefinition.getClazz();try {Object instance = clazz.getDeclaredConstructor().newInstance();//遍历所有字段,for(Field field : clazz.getDeclaredFields()) {//是否有Autowiredif(field.isAnnotationPresent(Autowired.class)) {String name = field.getName();//通过getBean获取要组装的对象Object bean = getBean(name);//进行组装,private需要暴破field.setAccessible(true);field.set(instance,bean);//将 bean 赋值给 instance 的 field}}System.out.println("======创建好实例======" + instance);//初始化方法前,调用before方法,可以对容器的bean实例进行处理,然后返回处理后的beanfor (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {Object current = beanPostProcessor.postProcessBeforeInitialization(instance, beanName);if(current != null)instance = current;}if(instance instanceof InitializingBean) {try {((InitializingBean) instance).afterPropertiesSet();//将instance转成InitializingBean类型,调用方法} catch (Exception e) {e.printStackTrace();}}//初始化方法后,调用after方法,可以对容器的bean实例进行处理,然后返回处理后的beanfor (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {Object current = beanPostProcessor.postProcessAfterInitialization(instance, beanName);if(current != null)instance = current;}return instance;

后置处理器接口BeanPostProcessor

对容器中的所有bean生效

public interface BeanPostProcessor {//bean的初始化前调用default Object postProcessBeforeInitialization(Object bean, String beanName) {return bean;}//bean的初始化后调用default Object postProcessAfterInitialization(Object bean, String beanName) {return bean;}
}

自己写一个类实现后置处理器,通过Component注入到容器中

实现类可以不止一个,放在Arraylist中

private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

@Component
public class HspBeanPostProcessor implements BeanPostProcessor {@Overridepublic Object postProcessBeforeInitialization(Object bean, String beanName) {System.out.println("后置处理器before()");return bean;}@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) {System.out.println("后置处理器after()");return bean;}
}

在HspApplicationContext的扫描方法中扫描Component,再判断是否实现了后置处理器接口

6、AOP机制实现 

原生Spring实现方法
A接口写方法,B类实现A接口,给B类加上@Component注入到容器
切面类加上@Component和@Aspect
B类执行后置处理器的After方法后,变成代理对象

public interface SmartAnimalable {float getSum(float i, float j);float getSub(float i, float j);
}
@Component(value = "smartDog")
public class SmartDog implements SmartAnimalable {public float getSum(float i, float j) {float res = i + j;System.out.println("SmartDog-getSum-res=" + res);return res;}public float getSub(float i, float j) {float res = i - j;System.out.println("SmartDog-getSub-res=" + res);return res;}
}
public class SmartAnimalAspect {public static void showBeginLog() {System.out.println("前置通知..");}public static void showSuccessLog() {System.out.println("返回通知..");}
}

在HspBeanPostProcessor的after方法中实现AOP(写死的方法)

public Object postProcessAfterInitialization(Object bean, String beanName) {System.out.println("后置处理器after()");if("smartDog".equals(beanName)) {Object proxyInstance = Proxy.newProxyInstance(HspBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {Object result = null;if("getSum".equals(method.getName())) {SmartAnimalAspect.showBeginLog();result = method.invoke(bean,args);SmartAnimalAspect.showSuccessLog();} else {result = method.invoke(bean,args);}return result;}});return proxyInstance;}return bean;}

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 0基础跟德姆(dom)一起学AI 数据处理和统计分析04-Panda入门
  • ArrayList和Array有什么区别?
  • 【RabbitMQ 项目】项目概述
  • 9.20-使用k8s部署wordpress项目
  • ELF文件结构
  • Git入门学习(1)
  • 基于协同过滤算法+PHP的新闻推荐系统
  • 详解Linux中cat命令
  • linux-安全管理-防火墙与网络安全
  • 硬件工程师笔试面试——开关
  • 【网络安全的神秘世界】攻防环境搭建及漏洞原理学习
  • 每日奇难怪题(持续更新)
  • Ceph 基本架构(一)
  • 用Go语言构建健壮的并发系统:深入理解错误传播与处理
  • oracle表的类型
  • 2017届校招提前批面试回顾
  • CSS3 变换
  • ES2017异步函数现已正式可用
  • es6要点
  • export和import的用法总结
  • Go 语言编译器的 //go: 详解
  • input的行数自动增减
  • laravel with 查询列表限制条数
  • leetcode388. Longest Absolute File Path
  • MQ框架的比较
  • MySQL的数据类型
  • vue2.0一起在懵逼的海洋里越陷越深(四)
  • Wamp集成环境 添加PHP的新版本
  • 持续集成与持续部署宝典Part 2:创建持续集成流水线
  • 猴子数据域名防封接口降低小说被封的风险
  • 目录与文件属性:编写ls
  • 前端设计模式
  • 前端自动化解决方案
  • -- 数据结构 顺序表 --Java
  • 问题之ssh中Host key verification failed的解决
  • 译自由幺半群
  • 微龛半导体获数千万Pre-A轮融资,投资方为国中创投 ...
  • 曜石科技宣布获得千万级天使轮投资,全方面布局电竞产业链 ...
  • ​​​​​​​ubuntu16.04 fastreid训练过程
  • ​【原创】基于SSM的酒店预约管理系统(酒店管理系统毕业设计)
  • ​你们这样子,耽误我的工作进度怎么办?
  • ​字​节​一​面​
  • # Python csv、xlsx、json、二进制(MP3) 文件读写基本使用
  • # Pytorch 中可以直接调用的Loss Functions总结:
  • #if和#ifdef区别
  • (11)MSP430F5529 定时器B
  • (2009.11版)《网络管理员考试 考前冲刺预测卷及考点解析》复习重点
  • (70min)字节暑假实习二面(已挂)
  • (BAT向)Java岗常问高频面试汇总:MyBatis 微服务 Spring 分布式 MySQL等(1)
  • (js)循环条件满足时终止循环
  • (MTK)java文件添加简单接口并配置相应的SELinux avc 权限笔记2
  • (八)Flink Join 连接
  • (附源码)springboot猪场管理系统 毕业设计 160901
  • (附源码)SSM环卫人员管理平台 计算机毕设36412
  • (附源码)计算机毕业设计ssm本地美食推荐平台