@Autowired内部实现原理


@Autowired
private CustomerDao customerDao;
        
public void addCustomer() {
    
    customerDao.addCustomer();
    
    }


public static void main(String[] args) {
        Class clazz = CustomerServiceImpl.class;
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            boolean present = field.isAnnotationPresent(Autowired.class);
            if(present){
                System.out.println(field.getGenericType());
                System.out.println(field.getName());
            }
        }
    }
    这应该就是spring里面的一段源码
    他是先获取当前类的.class文件
    然后再通过反射的方式获取字段
    然后遍历字段
    然后暴力反射获取注解的.class文件
    然后判断这个文件是否存在不
    如果存在,打印他的接口类型
    上面这段代码出来的效果如下:
    interface cn.ql.dao.CustomerDao
    customerDao
    然后我又定义了个属性方便理解
        @Autowired
        private String user;
        
        他出来的结果是
        class java.lang.String
        user

原文地址:https://www.cnblogs.com/guanzhuang/p/7679565.html