IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> 手写spring -> 正文阅读

[Java知识库]手写spring

参考视频

https://www.bilibili.com/video/BV1tR4y1F75R?p=1

目录

在这里插入图片描述

手写spring

在这里插入图片描述
Test

package com.zs.service;

import com.zs.spring.ZsApplicationContext;

public class Test {
    public static void main(String[] args) {
        //1. 需要有spring容器
        ZsApplicationContext zsApplicationContext = new ZsApplicationContext(AppConfig.class);
        UserService userService = (UserService) zsApplicationContext.getBean("userService");
    }
}

UserService

package com.zs.service;


import com.zs.spring.Component;

@Component("userService")
public class UserService {

}

ZsApplicationContext

package com.zs.spring;

public class ZsApplicationContext {
    private Class configClass;

    public ZsApplicationContext(Class configClass) {
        this.configClass = configClass;
    }

    public Object getBean(String beanName) {
        return null;
    }
}

Component

package com.zs.spring;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME) //生效时间
@Target(ElementType.TYPE) //只能写在类上面
public @interface Component {
    String value() default "";
}

ComponentScan

package com.zs.spring;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME) //生效时间
@Target(ElementType.TYPE) //只能写在类上面
public @interface ComponentScan {
    String value() default "";
}

AppConfig

package com.zs.service;


import com.zs.spring.ComponentScan;

@ComponentScan("com.zs.service")
public class AppConfig {
}

模拟扫描

package com.zs.spring;

import com.sun.media.sound.SoftTuning;

import java.io.File;
import java.net.URL;

public class ZsApplicationContext {
    private Class configClass;

    public ZsApplicationContext(Class configClass) {
        this.configClass = configClass;

        //模拟扫描
        if (configClass.isAnnotationPresent(ComponentScan.class)){
            ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            String path = componentScanAnnotation.value();//扫描路径 com.zs.service

            path = path.replace(".","/"); // com/zs/service

            //使用类加载器获取相对路径
            ClassLoader classLoader = ZsApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);
            File file = new File(resource.getFile());

//            System.out.println(file);

            if (file.isDirectory()){
                File[] files = file.listFiles();
                for (File f : files) {
                    String fileName = f.getAbsolutePath();
//                    System.out.println(fileName);
                    if (fileName.endsWith(".class")){
                        try {
                            String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                            className = className.replace("/",".");

                            System.out.println(className);

                            Class<?> clazz = classLoader.loadClass(className);

                            if (clazz.isAnnotationPresent(Component.class)){
                                //bean
                                
                                
                            }
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }


        }
    }

    public Object getBean(String beanName) {
        return null;
    }
}

模拟BeanDefinition

Scope

package com.zs.spring;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME) //生效时间
@Target(ElementType.TYPE) //只能写在类上面
public @interface Scope {
    String value() default "";
}

在这里插入图片描述
BeanDefinition

package com.zs.spring;

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

    public Class getType() {
        return type;
    }

    public void setType(Class type) {
        this.type = type;
    }

    public String getScope() {
        return scope;
    }

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

ZsApplicationContext

package com.zs.spring;

import com.sun.media.sound.SoftTuning;

import java.io.File;
import java.net.URL;
import java.util.concurrent.ConcurrentHashMap;

public class ZsApplicationContext {
    private Class configClass;

    private ConcurrentHashMap<String,BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();

    public ZsApplicationContext(Class configClass) {
        this.configClass = configClass;

        //模拟扫描
        if (configClass.isAnnotationPresent(ComponentScan.class)){
            ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            String path = componentScanAnnotation.value();//扫描路径 com.zs.service

            path = path.replace(".","/"); // com/zs/service

            //使用类加载器获取相对路径
            ClassLoader classLoader = ZsApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);
            File file = new File(resource.getFile());

//            System.out.println(file);

            if (file.isDirectory()){
                File[] files = file.listFiles();
                for (File f : files) {
                    String fileName = f.getAbsolutePath();
//                    System.out.println(fileName);
                    if (fileName.endsWith(".class")){



                        try {
                            String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                            className = className.replace("/",".");

                            System.out.println(className);

                            Class<?> clazz = classLoader.loadClass(className);



                            if (clazz.isAnnotationPresent(Component.class)){
                                //BeanDefinition

                                Component component = clazz.getAnnotation(Component.class);
                                String beanName = component.value();

                                BeanDefinition beanDefinition = new BeanDefinition();
                                beanDefinition.setType(clazz);

                                if (clazz.isAnnotationPresent(Scope.class)){
                                    Scope scopeAnnotation = clazz.getAnnotation(Scope.class);
                                    beanDefinition.setScope(scopeAnnotation.value());
                                }else{
                                    beanDefinition.setScope("singleton");
                                }

                                //将扫描出得bean定义对象放入集合中
                                beanDefinitionMap.put(beanName,beanDefinition);
                            }
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }



                    }
                }
            }


        }
    }

    public Object getBean(String beanName) {
        return null;
    }
}

模拟getBean

package com.zs.spring;

import com.sun.media.sound.SoftTuning;

import java.io.File;
import java.net.URL;
import java.util.concurrent.ConcurrentHashMap;

public class ZsApplicationContext {
    private Class configClass;

    //bean定义池
    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
    //单例池
    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();

    public ZsApplicationContext(Class configClass) {
        this.configClass = configClass;

        //模拟扫描
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            String path = componentScanAnnotation.value();//扫描路径 com.zs.service

            path = path.replace(".", "/"); // com/zs/service

            //使用类加载器获取相对路径
            ClassLoader classLoader = ZsApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);
            File file = new File(resource.getFile());

//            System.out.println(file);

            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    String fileName = f.getAbsolutePath();
//                    System.out.println(fileName);
                    if (fileName.endsWith(".class")) {


                        try {
                            String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                            className = className.replace("/", ".");

                            System.out.println(className);

                            Class<?> clazz = classLoader.loadClass(className);


                            if (clazz.isAnnotationPresent(Component.class)) {
                                //BeanDefinition

                                Component component = clazz.getAnnotation(Component.class);
                                String beanName = component.value();

                                BeanDefinition beanDefinition = new BeanDefinition();
                                beanDefinition.setType(clazz);

                                if (clazz.isAnnotationPresent(Scope.class)) {
                                    Scope scopeAnnotation = clazz.getAnnotation(Scope.class);
                                    beanDefinition.setScope(scopeAnnotation.value());
                                } else {
                                    beanDefinition.setScope("singleton");
                                }

                                //将扫描出得bean定义对象放入集合中
                                beanDefinitionMap.put(beanName, beanDefinition);
                            }
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

        //遍历出单例bean
        for (String beanName : beanDefinitionMap.keySet()) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if (beanDefinition.getScope().equals("singleton")){
                //将单例bean放入到单例池中
                Object bean =  createBean(beanName,beanDefinition);
                singletonObjects.put(beanName,bean);
            }
        }
    }
    private Object createBean(String beanName,BeanDefinition beanDefinition){

        //bean 创建
        return null;
    }


    public Object getBean(String beanName) {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition == null) {
            throw new NullPointerException();
        } else {
            String scope = beanDefinition.getScope();
            if (scope.equals("singleton")){
                //单例
                Object bean = singletonObjects.get(beanName);
                if (bean == null){
                    Object o = createBean(beanName,beanDefinition);
                    singletonObjects.put(beanName,0);
                }
                return bean;
            }else{
                //多例
                return createBean(beanName,beanDefinition);
            }
        }
    }
}

createBean方法实现

    private Object createBean(String beanName,BeanDefinition beanDefinition){

        //bean 创建
        Class clazz = beanDefinition.getType();
        try {
            Object instance = clazz.getConstructor().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;
    }

测试单例,多例

package com.zs.service;

import com.zs.spring.ZsApplicationContext;

public class Test {
    public static void main(String[] args) {
        //1. 需要有spring容器
        ZsApplicationContext zsApplicationContext = new ZsApplicationContext(AppConfig.class);
//        UserService userService = (UserService) zsApplicationContext.getBean("userService");
        System.out.println(zsApplicationContext.getBean("userService"));
        System.out.println(zsApplicationContext.getBean("userService"));
        System.out.println(zsApplicationContext.getBean("userService"));
    }
}

模拟依赖注入

扫描时如果没有给名称默认给类名

  //如果没有自定义bean名称,取类名第一字母小写
  if (beanName.equals("")){
      beanName = Introspector.decapitalize(clazz.getSimpleName());
  }

OrderService

package com.zs.service;


import com.zs.spring.Component;
import com.zs.spring.Scope;

@Component
public class OrderService {

}

测试

package com.zs.service;

import com.zs.spring.ZsApplicationContext;

public class Test {
    public static void main(String[] args) {
        //1. 需要有spring容器
        ZsApplicationContext zsApplicationContext = new ZsApplicationContext(AppConfig.class);
//        UserService userService = (UserService) zsApplicationContext.getBean("userService");
        System.out.println(zsApplicationContext.getBean("userService"));
        System.out.println(zsApplicationContext.getBean("userService"));
        System.out.println(zsApplicationContext.getBean("userService"));
        System.out.println(zsApplicationContext.getBean("orderService"));
    }
}

package com.zs.spring;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME) //生效时间
@Target(ElementType.FIELD) //只能写在属性上
public @interface Autowired {

}

UserService


package com.zs.service;


import com.zs.spring.Autowired;
import com.zs.spring.Component;
import com.zs.spring.Scope;

@Component("userService")
public class UserService {

    @Autowired
    private OrderService orderService;

    public void test(){
        System.out.println(orderService);
    }
}

测试,获取为null

package com.zs.service;

import com.zs.spring.ZsApplicationContext;

public class Test {
    public static void main(String[] args) {
        //1. 需要有spring容器
        ZsApplicationContext zsApplicationContext = new ZsApplicationContext(AppConfig.class);
        UserService userService = (UserService) zsApplicationContext.getBean("userService");
        userService.test();
    }
}

依赖注入简单版实现

private Object createBean(String beanName,BeanDefinition beanDefinition){

        //bean 创建
        Class clazz = beanDefinition.getType();
        try {
            Object instance = clazz.getConstructor().newInstance();


            //简单版依赖注入
            //获取所有属性,给有注解的属性添加值
            for (Field f : clazz.getDeclaredFields()) {
                if (f.isAnnotationPresent(Autowired.class)){
                    f.setAccessible(true);
                    f.set(instance,getBean(f.getName()));
                }
            }


            return instance;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

Aware回调

依赖注入以后判断是否 实现了 BeanNameAware接口,实现回调

private Object createBean(String beanName,BeanDefinition beanDefinition){

        //bean 创建
        Class clazz = beanDefinition.getType();
        try {
            Object instance = clazz.getConstructor().newInstance();


            //简单版依赖注入
            //获取所有属性,给有注解的属性添加值
            for (Field f : clazz.getDeclaredFields()) {
                if (f.isAnnotationPresent(Autowired.class)){
                    f.setAccessible(true);
                    f.set(instance,getBean(f.getName()));
                }
            }

            //依赖注入以后判断是否 实现了 BeanNameAware接口,实现回调
            if (instance instanceof BeanNameAware){
                ((BeanNameAware)instance).setBeanName(beanName);
            }


            return instance;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }
package com.zs.spring;

public interface BeanNameAware {
    void setBeanName(String beanName);
}

测试

package com.zs.service;


import com.zs.spring.Autowired;
import com.zs.spring.Component;
import com.zs.spring.Scope;

@Component("userService")
public class UserService {

    @Autowired
    private OrderService orderService;

    public void test(){
        System.out.println(orderService);
        System.out.println(orderService.getBeanName());
    }
}

package com.zs.service;


import com.zs.spring.BeanNameAware;
import com.zs.spring.Component;
import com.zs.spring.Scope;

@Component
public class OrderService implements BeanNameAware {

    private String beanName;

    public String getBeanName() {
        return beanName;
    }

    @Override
    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }
}

初始化回调

    private Object createBean(String beanName,BeanDefinition beanDefinition){

        //bean 创建
        Class clazz = beanDefinition.getType();
        try {
            Object instance = clazz.getConstructor().newInstance();


            //简单版依赖注入
            //获取所有属性,给有注解的属性添加值
            for (Field f : clazz.getDeclaredFields()) {
                if (f.isAnnotationPresent(Autowired.class)){
                    f.setAccessible(true);
                    f.set(instance,getBean(f.getName()));
                }
            }

            //依赖注入以后判断是否 实现了 BeanNameAware接口,实现回调
            if (instance instanceof BeanNameAware){
                ((BeanNameAware)instance).setBeanName(beanName);
            }

            //初始化
            if (instance instanceof InitializingBean){
                ((InitializingBean)instance).afterPropertiesSet();
            }

            return instance;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

模拟BeanPostProcessor

package com.zs.spring;

public interface BeanPostProcessor {
    void postProcessBeforeInitialization(String beanName,Object bean);
    void postProcessAfterInitialization(String beanName,Object bean);
}

    private ArrayList<BeanPostProcessor> beanPostProcessorsList = new ArrayList<>();



构造方法中
    if (clazz.isAnnotationPresent(Component.class)) {
        //该类上是否实现BeanPostProcessor接口
        if (BeanPostProcessor.class.isAssignableFrom(clazz)){
            BeanPostProcessor instance = (BeanPostProcessor) clazz.newInstance();
            beanPostProcessorsList.add(instance);
        }




createBean方法中
    for (BeanPostProcessor beanPostProcessor : beanPostProcessorsList) {
        beanPostProcessor.postProcessBeforeInitialization(beanName,instance);
    }

    //初始化
    if (instance instanceof InitializingBean){
        ((InitializingBean)instance).afterPropertiesSet();
    }

    for (BeanPostProcessor beanPostProcessor : beanPostProcessorsList) {
        beanPostProcessor.postProcessAfterInitialization(beanName,instance);
    }

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-03-22 20:22:50  更:2022-03-22 20:23:36 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 9:02:33-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码