【Spring】我抄袭了Spring,手写一套MySpring框架。。。

news/2024/7/7 20:35:29

这篇博客实现了一个简单版本的Spring,主要包括Spring的Ioc和Aop功能

文章目录

  • 这篇博客实现了一个简单版本的Spring,主要包括Spring的Ioc和Aop功能
    • 🚀@ComponentScan注解
    • ✈️@Component注解
    • 🚁在spring中ioc容器的类是ApplicationContext
    • 🚂测试类
    • 🚊MySpringConfig类,统一的配置类
    • 🚞OrderService类,一个普通的bean
      • 🚲来测试一下功能
    • 🚡@Scope注解
    • 🚟BeanDefinition 类
      • 🚠要实现我们的@scope注解,我们需要改造一下我们的代码
      • 🚜然后我们从beanDefinitionMap中实例化bean
      • 🚙我们来看一下效果
    • 🚘@Autowired注解
    • 🚗UserService类,orderservice注入该类
      • 🚗要使@Autowired注解生效,将bean实例化到一级缓存中方法需要改造一下
    • 🚕BeanPostProcessor接口
    • 🚖添加自己的BeanPostProcessor
    • 🚛Aop

🚀@ComponentScan注解

ComponentScan做的事情就是告诉Spring从哪里找到bean

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ComponentScan {

	String[] value() default {};

}

✈️@Component注解

@Component是spring中的一个注解,它的作用就是实现bean的注入

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {

	String value() default "";


}

🚁在spring中ioc容器的类是ApplicationContext

所以我们需要创建一个ApplicationContext,有参构造传入config的class

public class ApplicationContext {

    public ApplicationContext(Class configClass) {
    
    }
    
}

存放bean的map

public class ApplicationContext {

 	private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
 
    public ApplicationContext(Class configClass) {
    
    }
    
}

拿到ComponentScan的值

public class ApplicationContext {

    private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);


    public ApplicationContext(Class configClass) {
        //查看是否有ComponentScan注解
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            String[] paths = componentScanAnnotation.value();
           
        }
    }
}

拿到该路径下所有的class文件

public class ApplicationContext {

    private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);


    public ApplicationContext(Class configClass) {
        //查看是否有ComponentScan注解
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            String[] paths = componentScanAnnotation.value();
            for (String path : paths) {

                //拿到包路径
                ClassLoader classLoader = ApplicationContext.class.getClassLoader();
                URL resource = classLoader.getResource(path.replace(".", "/"));
                //拿到该路径下所有的class文件
                File file = new File(resource.getFile());
                if (file.isDirectory()) {
                    File[] files = file.listFiles();
                    for (File f : files) {
                     
                    }
                }
            }
        }
    }
}

注册有Component注解的bean

public class ApplicationContext {

    private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);


    public ApplicationContext(Class configClass) {
        //查看是否有ComponentScan注解
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            String[] paths = componentScanAnnotation.value();
            for (String path : paths) {

                //拿到包路径
                ClassLoader classLoader = ApplicationContext.class.getClassLoader();
                URL resource = classLoader.getResource(path.replace(".", "/"));
                //拿到该路径下所有的class文件
                File file = new File(resource.getFile());
                if (file.isDirectory()) {
                    File[] files = file.listFiles();
                    for (File f : files) {
                        try {
                            String filePath = f.getPath();
                            //拿到com.masiyi.service.MySpringConfig
                            String sub = filePath.substring(filePath.indexOf("com"), filePath.indexOf(".class"));
                            String classes = sub.replace("\\", ".");
                            Class<?> aClass = classLoader.loadClass(classes);
                            //注册有Component注解的bean
                            if (aClass.isAnnotationPresent(Component.class)) {
                                Object bean = aClass.getDeclaredConstructor().newInstance();
                                Component component = aClass.getAnnotation(Component.class);
                                String beanName = component.value();
                                if ("".equals(beanName) || beanName == null) {
                                    singletonObjects.put(f.getName().split("\\.")[0], bean);
                                } else {
                                    singletonObjects.put(beanName, bean);
                                }
                            }
                        } catch (ClassNotFoundException | InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

🚂测试类

现在我们最基础的spring的ioc已经基本实现了,我们新建一个测试类来测试

public class Test {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ApplicationContext(MySpringConfig.class);

    }
}

🚊MySpringConfig类,统一的配置类

@ComponentScan("com.masiyi.service")
public class MySpringConfig {

}

🚞OrderService类,一个普通的bean

@Component
public class OrderService {
}

🚲来测试一下功能

拿到包路径

在这里插入图片描述

拿到该路径下所有的class文件

在这里插入图片描述

注册有Component注解的bean

在这里插入图片描述

注册进ioc

在这里插入图片描述

getBean方法

  public Object getBean(String beanName) {
        return this.singletonObjects.get(beanName);
    }

在这里插入图片描述

🚡@Scope注解

@Scope注解是 Spring IOC 容器中的一个作用域

🚟BeanDefinition 类

BeanDefinition 是定义 Bean 的配置元信息接口,可以理解为创建bean过程中的一个中间类,扩展bean,存储更多的信息

public class BeanDefinition {
    private String scope;
    private Class aClass;

    public String getScope() {
        return scope;
    }

    public void setScope(String scope) {
        this.scope = scope;
    }

    public Class getaClass() {
        return aClass;
    }

    public void setaClass(Class aClass) {
        this.aClass = aClass;
    }
}

🚠要实现我们的@scope注解,我们需要改造一下我们的代码

把createBean方法抽离出来

  private void createBean(String beanName,Class<?> aClass){
        //注册有Component注解的bean
        if (aClass.isAnnotationPresent(Component.class)) {

            Component component = aClass.getAnnotation(Component.class);
            BeanDefinition beanDefinition = new BeanDefinition();
            if (aClass.isAnnotationPresent(Scope.class)) {
                Scope scope = aClass.getAnnotation(Scope.class);
                beanDefinition.setScope(scope.value());
            } else {
                beanDefinition.setScope("singleton");
            }
            beanDefinition.setaClass(aClass);

            String value = component.value();
            if ("".equals(value)) {
                beanDefinitionMap.put(beanName, beanDefinition);
            } else {
                beanDefinitionMap.put(value, beanDefinition);
            }
        }
    }

扫描ComponentScan注解的方法体改一下

🚜然后我们从beanDefinitionMap中实例化bean


        //将bean实例化到一级缓存中
        for (String beanName : beanDefinitionMap.keySet()) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            //单例
            if ("singleton".equals(beanDefinition.getScope())) {
                try {
                    Object bean = beanDefinition.getaClass().getDeclaredConstructor().newInstance();
                    singletonObjects.put(beanName, bean);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

getBean方法也需要改造

public Object getBean(String beanName) {
        BeanDefinition beanDefinition = this.beanDefinitionMap.get(beanName);
        if (beanDefinition == null) {
            throw new NullPointerException();
        }
        if ("singleton".equals(beanDefinition.getScope())) {
            //如果是单例,直接返回缓存里的bean
            return this.singletonObjects.get(beanName);
        } else {
            try {
                //如果是多例,直接返回新的bean
                return beanDefinition.getaClass().getDeclaredConstructor().newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

🚙我们来看一下效果

在这里插入图片描述

这是没有加scope注解

在这里插入图片描述
返回的bean都是一个对象

我们给bean加上scope注解

在这里插入图片描述
返回来的bean每个都不一样

在这里插入图片描述

🚘@Autowired注解

spring中实现依赖注入的注解

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Autowired {

}

🚗UserService类,orderservice注入该类

@Component("userService")
public class UserService {
}

@Component
public class OrderService {
    @Autowired
    private UserService userService;


    public UserService getUserService() {
        return userService;
    }
}

🚗要使@Autowired注解生效,将bean实例化到一级缓存中方法需要改造一下

在这里插入图片描述

新增populateBean方法,用来初始bean


    private void populateBean(Object bean, Class aClass) {
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            if (declaredField.isAnnotationPresent(Autowired.class)) {
                declaredField.setAccessible(true);
                try {
                    declaredField.set(bean, getBean(declaredField.getName()));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

getBean方法也需要改造一下

在这里插入图片描述

这样我们的orderservice里面的userservice就有值了

在这里插入图片描述

🚕BeanPostProcessor接口

该接口在显示调用初始化方法的前后添加我们自己的逻辑

public interface BeanPostProcessor {
    /**
     * 之前
     * @param bean
     * @param beanName
     * @return
     */
    default Object postProcessBeforeInitialization(Object bean, String beanName) {
        return bean;
    }

    /**
     * 之后
     * @param bean
     * @param beanName
     * @return
     */
    default Object postProcessAfterInitialization(Object bean, String beanName) {
        return bean;
    }
}

我们创建存储BeanPostProcessor的list

在这里插入图片描述

在扫描的时候添加BeanPostProcessor

在这里插入图片描述

🚖添加自己的BeanPostProcessor

@Component
public class OrderPostProcessor implements BeanPostProcessor {
    /**
     * 之前
     *
     * @param bean
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        System.out.println(beanName+"执行前");
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    /**
     * 之后
     *
     * @param bean
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println(beanName+"执行后");
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}

实例化的时候执行BeanPostProcessor逻辑

在这里插入图片描述

运行结果

在这里插入图片描述

🚛Aop

jdk的动态代理是基于接口生成的代理对象

public interface OrderInterface {
    void test();
}

在这里插入图片描述

在OrderPostProcessor类中加以改造

在这里插入图片描述

这样我们就可以动态代理切入我们的orderservice类

在这里插入图片描述
在这里插入图片描述
以上就是全部内容

实现了以下

  • 🚀@ComponentScan注解
  • ✈️@Component注解
  • 🚁ApplicationContext类
  • 🚡@Scope注解
  • 🚟BeanDefinition 类
  • 🚘@Autowired注解
  • 🚕BeanPostProcessor接口
  • 🚛Aop
    内容,完成了一个超级简单且基础的spring源码

项目源码

博客码了两天,创作不易,多多点赞

在这里插入图片描述


http://lihuaxi.xjx100.cn/news/1007326.html

相关文章

工厂模式小结

工厂模式 作用&#xff1a;封装对象的创建 简单工厂 并不是一个设计模式&#xff0c;使用简单 工厂方法 提供一个接口&#xff0c;让子类决定实例化哪些对象。 父类定义一个抽象的方法&#xff0c;用于获取抽象的产品&#xff0c;使用继承的方式&#xff0c;让子类实现抽象…

插入运算符“>>“和提取运算符“<<“的重载

&#x1f436;博主主页&#xff1a;ᰔᩚ. 一怀明月ꦿ ❤️‍&#x1f525;专栏系列&#xff1a;线性代数&#xff0c;C初学者入门训练&#xff0c;题解C&#xff0c;C的使用文章&#xff0c;「初学」C &#x1f525;座右铭&#xff1a;“不要等到什么都没有了&#xff0c;才下…

缺失msvcrtd.dll怎么办?如何修复msvcrtd.dll文件

在日常使用电脑中&#xff0c;其实出现一些dll文件缺失是非常的正常的&#xff0c;这时候我们不需要慌张&#xff0c;只需要知道一些解决方法&#xff0c;那么就可以解决文件缺失问题&#xff0c;今天来给大家详细的讲解一下缺失msvcrtd.dll怎么办。 一.什么是msvcrtd.dll文件 …

口罩发放(C语言实现)

为了抗击来势汹汹的 COVID19 新型冠状病毒&#xff0c;全国各地均启动了各项措施控制疫情发展&#xff0c;其中一个重要的环节是口罩的发放。 某市出于给市民发放口罩的需要&#xff0c;推出了一款小程序让市民填写信息&#xff0c;方便工作的开展。小程序收集了各种信息&…

原来企业的生产管理这么简单

&#x1f31f;所属专栏&#xff1a;ERP企业资源管理&#x1f414;作者简介&#xff1a;rchjr——五带信管菜只因一枚&#x1f62e;前言&#xff1a;该系列将持续更新ERP的相关学习笔记&#xff0c;欢迎和我一样的小白订阅&#xff0c;一起学习共同进步~&#x1f449;文章简介&a…

WooCommerce可扩展性:如何扩大您的WooCommerce商店

有了合适的人和技术&#xff0c;WooCommerce可扩展性绝对是很大的&#xff01; 事实上&#xff0c;使用WooCommerce作为您的电子商务平台&#xff0c;您的在线商店的规模可以与您的目标和愿望一样大&#xff01; 根据自定义模板开发高性能品牌电子商务网站 全球超500万个电商…

本地打开dist文件

npm run build打包后 cd dist http-server 没有http-server&#xff0c;npm install -g http-server http-server

开源蜜罐hfish安装及使用教程

一、hfish安装 xshell上传hfish-3.3.1-linux-amd64.tgz 创建解压目录 [root@localhost ~]# mkdir hfish 解压 [root@localhost ~]# tar zxvfhfish-3.3.1-linux-amd64.tgz-C hfish 防火墙开启4433、4434和7879,确认返回success。 [root@localhost ~]# iptables -I INPUT -…