35.学源码最快的方式:带你手写一个Spring

简单实现以下spring流程

UserService.class > 无参构造方法 (推断构造方法)> 普通对象 > 依赖注入(属性赋值) > 初始化前@PostConstruct > 初始化InitializingBean > 初始化后(AOP)> 代理对象 > Bean

关于里面实现的代理对象,看起来像是栈逻辑

courseService执行after切面逻辑 com.lywtimer.service.MyBeanPostProcessor
courseService执行after切面逻辑 com.lywtimer.service.FilterBeanPostProcessor
courseService执行before切面逻辑
CourseService Testing

代码中 postProcessBeforeInitialization 和 postProcessAfterInitialization 的实现并不合理,感觉也没有必要


package com.spring;

import com.lywtimer.AppConfig;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyApplicationContext {

    private Class configClass;
    private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();
    private Map<String, Object> singletonObjects = new HashMap<>();
    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public MyApplicationContext(Class<AppConfig> configClass) {
        this.configClass = configClass;
        //扫描class文件,获取Bean
        scan(configClass);
        //遍历扫描好的map
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            String beanName = entry.getKey();
            BeanDefinition beanDefinition = entry.getValue();
            if (beanDefinition.getScope().equals("singleton")) {
                //创建单例对象并存储
                Object instance = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, instance);
            }
        }
    }

    private Object createBean(String beanName, BeanDefinition beanDefinition) {
        Object instance = null;
        Class clazz = beanDefinition.getType();
        try {
            //选择构造方法
            Constructor constructor = clazz.getDeclaredConstructor();
            instance = constructor.newInstance();
            //遍历属性
            for (Field declaredField : clazz.getDeclaredFields()) {
                if (declaredField.isAnnotationPresent(Autowired.class)) {
                    //简单化处理,存在循环依赖问题
                    declaredField.setAccessible(true);
                    declaredField.set(instance, getBean(declaredField.getName()));
                }
            }
            //初始化前执行切面逻辑
            for (BeanPostProcessor processor : beanPostProcessorList) {
                instance = processor.postProcessBeforeInitialization(instance, beanName);
            }
            //初始化执行
            if (instance instanceof InitializingBean) {
                ((InitializingBean) instance).afterPropertiesSet();
            }
            //初始化后执行切面逻辑
            for (BeanPostProcessor processor : beanPostProcessorList) {
                instance = processor.postProcessAfterInitialization(instance, beanName);
            }
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException |
                 InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        return instance;
    }


    public Object getBean(String beanName) {
        if (!beanDefinitionMap.containsKey(beanName)) {
            throw new NullPointerException("Bean " + beanName + " not found ");
        }

        var beanDefinition = beanDefinitionMap.get(beanName);

        if (beanDefinition.getScope().equals("singleton")) {
            Object bean = singletonObjects.get(beanName);
            if (bean == null) {
                bean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, bean);
            }
            return bean;
        } else {
            //重新新建bean对象
            return createBean(beanName, beanDefinition);
        }
    }

    private void scan(Class<AppConfig> configClass) {
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            var annotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            String packageName = annotation.value();

            var path = packageName.replace(".", "/");
            //查找类加载器指定的目录
            ClassLoader classLoader = MyApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);
            //转换成目录文件读取
            File file = new File(resource.getFile());
            if (file.isDirectory()) {
                for (File f : file.listFiles()) {
                    String p = packageName + "." + f.getName().replace(".class", "");
                    try {
                        var clazz = classLoader.loadClass(p);
                        //查找Bean
                        if (clazz.isAnnotationPresent(Component.class)) {
                            //查找实现类
                            boolean find = BeanPostProcessor.class.isAssignableFrom(clazz);
                            if (find) {
                                BeanPostProcessor instance = (BeanPostProcessor) clazz.getDeclaredConstructor().newInstance();
                                beanPostProcessorList.add(instance);
                            }

                            //获取 beanName
                            String beanName = clazz.getAnnotation(Component.class).value();
                            if ("".equals(beanName)) {
                                beanName = Introspector.decapitalize(clazz.getSimpleName());
                            }
                            String scope = "singleton";
                            if (clazz.isAnnotationPresent(Scope.class)) {
                                scope = clazz.getAnnotation(Scope.class).value();
                            }
                            //构建BeanDefinition
                            var beanDefinition = new BeanDefinition();
                            beanDefinition.setType(clazz);
                            beanDefinition.setScope(scope);
                            beanDefinitionMap.put(beanName, beanDefinition);
                        }
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    } catch (InvocationTargetException e) {
                        throw new RuntimeException(e);
                    } catch (InstantiationException e) {
                        throw new RuntimeException(e);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    } catch (NoSuchMethodException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一个Spring的源码实现是一个非常复杂的任务,需要对Spring的核心原理和设计思想有深入的理解。以下是一个简单的Spring源码实现的示例,仅供参考。 首先,我们需要创建一个核心的容器类来管理Bean的生命周期和依赖注入。这个容器类需要实现BeanFactory接口,提供getBean()方法来获取Bean对象。 ```java public interface BeanFactory { Object getBean(String name); } ``` 接下来,我们需要实现一个简单的Bean定义类,用于描述Bean的属性和依赖关系。 ```java public class BeanDefinition { private Class<?> beanClass; private Map<String, Object> properties = new HashMap<>(); private List<PropertyValue> propertyValues = new ArrayList<>(); public void setBeanClass(Class<?> beanClass) { this.beanClass = beanClass; } public Class<?> getBeanClass() { return beanClass; } public void addProperty(String name, Object value) { properties.put(name, value); } public Object getProperty(String name) { return properties.get(name); } public List<PropertyValue> getPropertyValues() { return propertyValues; } public void addPropertyValue(PropertyValue propertyValue) { propertyValues.add(propertyValue); } } public class PropertyValue { private final String name; private final Object value; public PropertyValue(String name, Object value) { this.name = name; this.value = value; } public String getName() { return name; } public Object getValue() { return value; } } ``` 然后,我们需要实现一个简单的BeanFactory实现类,用于创建和管理Bean对象。这个实现类需要读取Bean定义信息,创建Bean实例,并将其保存在一个Map中。 ```java public class SimpleBeanFactory implements BeanFactory { private final Map<String, BeanDefinition> beanDefinitions = new HashMap<>(); private final Map<String, Object> beans = new HashMap<>(); public SimpleBeanFactory(String configLocation) { loadBeanDefinitions(configLocation); createBeans(); } private void loadBeanDefinitions(String configLocation) { // 从配置文件中读取Bean定义信息 } private void createBeans() { for (String beanName : beanDefinitions.keySet()) { createBean(beanName); } } private Object createBean(String beanName) { BeanDefinition beanDefinition = beanDefinitions.get(beanName); Class<?> beanClass = beanDefinition.getBeanClass(); Object bean = createInstance(beanClass); applyPropertyValues(bean, beanDefinition.getPropertyValues()); beans.put(beanName, bean); return bean; } private Object createInstance(Class<?> beanClass) { try { return beanClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } private void applyPropertyValues(Object bean, List<PropertyValue> propertyValues) { for (PropertyValue propertyValue : propertyValues) { String propertyName = propertyValue.getName(); Object value = propertyValue.getValue(); setPropertyValue(bean, propertyName, value); } } private void setPropertyValue(Object bean, String propertyName, Object value) { try { BeanUtils.setProperty(bean, propertyName, value); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } @Override public Object getBean(String name) { return beans.get(name); } } ``` 最后,我们需要实现一个简单的测试类来验证我们的实现是否正确。 ```java public class SimpleBeanFactoryTest { @Test public void testGetBean() { BeanFactory beanFactory = new SimpleBeanFactory("classpath:beans.xml"); TestBean testBean = (TestBean) beanFactory.getBean("testBean"); assertNotNull(testBean); assertNotNull(testBean.getDependency()); } } ``` 这只是一个简单的Spring源码实现示例,实际上Spring的源码实现要复杂得多,涉及到很多高级特性和设计模式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值