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
原文地址:https://www.cnblogs.com/xiaoruirui/p/14808260.html