手写spring

首先准备几个注解:

/**
 * @author 
 * @date 2022/5/28
 */
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.TYPE)
public @interface ComponentScan {
    String value() default "";
}
/**
 * @author 
 * @date 2022/5/28
 */
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.TYPE)
public @interface Component {
    String value() default "";
}
@Retention(value = RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Autowired {

}
/**
 * @author 
 * @date 2022/5/28
 */
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.TYPE)
public @interface Scope {
    String value() default "";
}

Appconfig:

/**
 * @author FaMing
 * @date 2022/5/28
 */
@ComponentScan("com.myspringtest.service")
public class AppConfig {
}

准备启动:

/**
 * @author FaMing
 * @date 2022/5/28
 */
public class Test {

    public static void main(String[] args) {
        MyAnnotationConfigApplication myAnnotationConfigApplication = new MyAnnotationConfigApplication(AppConfig.class);

        UserService userService = (UserService) myAnnotationConfigApplication.getBean("userService");
        OrderService orderService = (OrderService) myAnnotationConfigApplication.getBean("orderService");
        userService.test();
        orderService.sss();
    }
}

初始化接口:

/**
 * @author FaMing
 * @date 2022/5/29
 */
public interface InitializingBean {

    void afterPropertiesSet();
}

BeanDefinition:

package com.spring;

/**
 * @author FaMing
 * @date 2022/5/29
 */
public class BeanDefinition {


    private Class type;
    private String scope;
    private boolean isLazy;


    public BeanDefinition() {

    }

    public BeanDefinition(Class type, String scope, boolean isLazy) {
        this.type = type;
        this.scope = scope;
        this.isLazy = isLazy;
    }

    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;
    }

    public boolean isLazy() {
        return isLazy;
    }

    public void setLazy(boolean lazy) {
        isLazy = lazy;
    }
}

扩展接口初始化前后:

package com.spring;

/**
 * @author FaMing
 * @date 2022/5/29
 */
public interface BeanPostProcessor {
    //初始化方法前
    default Object postProcessBeforeInitialization(Object bean, String beanName) {
        return bean;
    }

    //初始化方法后
    default Object postProcessAfterInitialization(Object bean, String beanName) {
        return bean;
    }
}

自定义初始化前后:
初始化前:

package com.spring;

import java.lang.reflect.Field;

/**
 * @author FaMing
 * @date 2022/5/29
 */
@Component
public class MyBeforeBeanPostProcessor implements BeanPostProcessor{
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
         Field[] declaredFields = bean.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            myAnnotation annotation = field.getAnnotation(myAnnotation.class);
            String value = annotation.value();
            try {
                field.set(bean,field.get(value));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return bean;
    }
}

初始化后AOP:

package com.spring;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author FaMing
 * @date 2022/5/29
 */
@Component
public class MyAfterBeanPostProcessor implements BeanPostProcessor{
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        //假如只需要一个类使用aop代理逻辑,那么就做一个判断beanName是否相等即可
        Object proxyInstance = Proxy.newProxyInstance(MyAfterBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //执行代理逻辑
                // 切面
                System.out.println("切面逻辑");

                return method.invoke(bean, args);
            }

        });
        return proxyInstance;
    }
}

一系列方法:

package com.spring;

import java.beans.Introspector;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.*;

/**
 * @author FaMing
 * @date 2022/5/28
 */
public class MyAnnotationConfigApplication {

    private Class configClass;

    //定义此集合的目的就是存储类信息,目的就是区分单例和多列作为缓存
   private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();
    private Map<String, Object> singletonObjects = new HashMap<>();
    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    /**
     * 构造器
     * @param configClass
     */
    public MyAnnotationConfigApplication(Class configClass) {
        this.configClass = configClass;
        //扫描方法
        scan(configClass);
        //如果是单例bean那么就放入单例池中去
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            String beanName = entry.getKey();
            BeanDefinition beanDefinition = entry.getValue();
            if (beanDefinition.getScope().equals("singleton")) {

                Object bean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, bean);

            }
        }

    }

    /**
     * 扫描方法
     * @param configClass
     */
    private void scan(Class configClass) {
        //扫描的方法
        //1.首先确认加载的类扫描是否存在@ComponentScan注解
        if (configClass.isAnnotationPresent(ComponentScan.class)){
            //如果存在,那么需要获取target目录下的java.class文件
            //1.获取注解上的扫描路径
            ComponentScan annotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            //获取到注解上扫描的路径
             String path = annotation.value();
            String replace = path.replace(".", "/");
            //打印结果:获取@ComponentScan上的路径com/myspringtest/service
            System.out.println("获取@ComponentScan上的路径"+replace);
            //2.如果要操作这些类,那么我们都是获取的是target目录下的java.class反编译得到数据为准,
            // 而我们自己写的类就是应用程序类加载器去加载的,获取类加载器
            ClassLoader classLoader = MyAnnotationConfigApplication.class.getClassLoader();
            URL resource = classLoader.getResource(replace);
            File file = new File(resource.getFile());

            //判断文件是否存在,如果存在就遍历所有的文件,然后反编译成我们的class文件,我们就可以使用反射对其操作了
            if (file.isDirectory()){
                //遍历所有文件
                for (File listFile : file.listFiles()) {
                    //得到每一个文件的路径
                    String absolutePath = listFile.getAbsolutePath();
                    //打印结果:D:\springCloudAlibaba\my_spring\target\classes\com\myspringtest\service\UserService.class
                    System.out.println("获取每一个文件的绝对路径:"+absolutePath);

                    //将路径替换
                    String substringUrl = absolutePath.substring(absolutePath.indexOf("com"), absolutePath.indexOf(".class"));
                    //替换
                    String repUrl = substringUrl.replace("\\", ".");
                    //打印结果:com.myspringtest.service.UserService
                    System.out.println("将绝对路径转化为类加载器需要的路径:"+repUrl);


                    try {
                        //使用类加载器获取class字节码
                        Class<?> aClass = classLoader.loadClass(repUrl);

                        //通过字节码文件获取类,判断类上是否存在Component注解,如果存在就需要
                        //判断是否单例,如果是单例,就加入单例池中,如果不是单例就继续走创建bean流程
                        BeanDefinition beanDefinition = new BeanDefinition();
                        beanDefinition.setType(aClass);


                        //将我们的对象加入缓存做为扩展类,再创建的时候做初始化的时候使用
                        //这里是扩展类,初始化前初始化后使用
                        if (BeanPostProcessor.class.isAssignableFrom(aClass)) {
                            BeanPostProcessor instance = (BeanPostProcessor) aClass.getConstructor().newInstance();
                            beanPostProcessorList.add(instance);
                        }

                        //获取beanName
                        Component component = aClass.getAnnotation(Component.class);
                        String beanName = component.value();
                        //如果@Component注解上没有指定beanName那么就让类名小写默认为beanName
                        if ("".equals(beanName)){
                            beanName = Introspector.decapitalize(aClass.getSimpleName());
                        }


                        //判断此类是否是单例,还是原型类,如果类上加入了@Scope注解的话,那么就会每一次getBean的时候都会去走创建流程
                        if (aClass.isAnnotationPresent(Scope.class)){
                            //直接将它的value给beanDefinition
                            Scope scope = aClass.getAnnotation(Scope.class);
                            String value = scope.value();
                            beanDefinition.setScope(value);
                        }else {
                            //表示单例bean
                            beanDefinition.setScope("singleton");
                        }
                        //加入MAP缓存
                        beanDefinitionMap.put(beanName,beanDefinition);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }


    /**
     * 获取bean
     * @param beanName
     * @return
     */
    public Object getBean(String beanName) {
        //如果我们扫描的时候没有这个beanName,那么就说明操作的时候没有这个类的生产
        if (!beanDefinitionMap.containsKey(beanName)){
            throw new NullPointerException();
        }
        //根据beanName获取value
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        //判断是单例还是原型类
        //如果是单例
        if (beanDefinition.getScope().equals("singleton")){
            //那么就从单例池中去拿对象
            Object singletonBean = singletonObjects.get(beanName);
            //如果单例池中没有,那么就创建bean
            if (Objects.isNull(singletonBean)){
                singletonBean=createBean(beanName,beanDefinition);
                singletonObjects.put(beanName,singletonBean);
            }
            return singletonBean;

        }else {
            // 如果是原型类,也就是多例类,直接创建逻辑
            Object prototypeBean = createBean(beanName, beanDefinition);
            return prototypeBean;
        }
    }

    /**
     * 创建bean的逻辑
     * @param beanName
     * @param beanDefinition
     * @return
     */
    private Object createBean(String beanName, BeanDefinition beanDefinition) {
        //获取当前类
       Class clazz = beanDefinition.getType();
       //创建对象
        Object instance=null;
        try {
            instance=clazz.getDeclaredConstructor().newInstance();
            //进行依赖注入
            //获取当前类所有的属性
           Field[] fields = instance.getClass().getDeclaredFields();
           //遍历所有的属性值并判断是否是依赖注入
            for (Field field : fields) {
                //如果属性存在注入的注解,这里不仅仅只是Autowired
                if (field.isAnnotationPresent(Autowired.class)){
                    field.setAccessible(true);
                    //从单例池中去拿,或者继续走创建,会造成循环依赖
                    field.set(instance, getBean(field.getName()));
                }

            }
            //设置Aware的回调接口
            //判断当前类是否实现了Aware接口
            if (instance instanceof BeanNameAware){
                ((BeanNameAware) instance).setBeanName(beanName);
            }
            //初始化之前
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance= beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
            }

            //初始化
            //目的就是初始化我们的接口方法,去实现一些我们自己的逻辑
            if (instance instanceof InitializingBean){
                ((InitializingBean) instance).afterPropertiesSet();
            }

            //初始化之后,做aop
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                beanPostProcessor.postProcessAfterInitialization(instance,beanName);
            }



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

        return instance;
    }

}

扫描方法:
扫描路径,主要是获取到我们编译的.class文件转化为类,然后做操作
1.判断类上是否存在@ComponentScan注解
2.获取到value扫描路径,然后获取到扫描路径中所有的类
3.判断类是否与BeanPostProcessor初始化扩展类关联,如果关联,将类信息丢到初始化集合中去,方便创建使用
4.判断是否存在@Component 注解,存在继续判断是否存在beanName,如果不存在,那么默认给他一个beanName
5.判断是否存在@Scope是否是单例,或者原型类,将其加入BeanDefinition的Map缓存中去(beanDefinitionMap)
6.在我们构造方法中还会去判断如果是单例就走createBean方法将返回对象存储到
单例池中去

getBean方法:
1.根据beanName去到beanDefinitionMap内拿到BeanDefinition
2.判断BeanDefinition中的type也就是我们的类是否存在,是否是单例,如果是那么就去单例池中去拿,如果存在直接返回当前类,不存在就调用createBean方法进行创建之后返回,如果是原型bean那么就调用createBean方法去构建bean然后返回;

createBean方法:
1.根据推断构造器创建类对象
2.判断是否存在依赖注入的注解,存在就进行注入
3.判断有没有实现一些Aware的接口,做回调的
4.初始化之前,也就是执行我们的逻辑
5.初始化,当前类有没有实现InitializingBean接口,也是实现我们的逻辑
6.初始化后的方法(是否符合AOP)
我们的bean就创建出来了,注意如果符合AOP的情况,创建出来的就是代理类,并非我们的被代理类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值