• Spring源码解析2


    在上个版本中我们能够实现一些基础的功能我们需要改进的地方

    1.添加Autowired注解及实现

    package cn.jiedada.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 {
        boolean required() default true;
    }

    添加注解效仿Spring源码

    我们需要思考的是在什么时候赋值进去

    坑定是createBean的时候所以需要在添加反射方法像对象中获取值

    public Object createBean(String beanName,BeanDefinition beanDefinition){
            Class clazz = beanDefinition.getClazz();
            Object instance = null;
            try {
                instance = clazz.newInstance();
    
                //依赖注入
                //clazz.getDeclaredFields()获取类中的字段
                for (Field field : clazz.getDeclaredFields()) {
                    //通过反射的方式
                    if (field.isAnnotationPresent(Autowired.class)) {
                        String name = field.getName();
                        Object bean = getBean(name);
                        field.setAccessible(true);
                        field.set(instance,bean);
                    }
                }
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return instance;
        }
    View Code
  • 相关阅读:
    性能分析与调优思想
    python散列实现映射抽象数据类型
    python接口模拟100个用户登录
    大O记法
    linux查看操作系统版本信息
    Python招聘信息
    flask-login模块官网内容整理
    python|base|环境搭建
    echarts|map
    mysql|unsigned 与 signed 类型
  • 原文地址:https://www.cnblogs.com/xiaoruirui/p/14808260.html
Copyright © 2020-2023  润新知