spring源码1--自定义Autowired实现

以下为目录结构
在这里插入图片描述
以下为代码具体实现

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Inherited
@Documented
public @interface Autowired {
    
    
}
public class UserService {
    
    
}
public class UserController {
    
    

    @Autowired
    private UserService userService;

    public UserService getUserService() {
    
    
        return userService;
    }
}
import java.util.stream.Stream;

public class TestMain {
    
    
    public static void main(String[] args){
    
    
        UserController userController=new UserController();
        Class<? extends UserController> clazz=userController.getClass();
        Stream.of(clazz.getDeclaredFields()).forEach(field -> {
    
    
            Autowired annotation=field.getAnnotation(Autowired.class);
            if(annotation!=null){
    
    
                field.setAccessible(true);//私有成员需要设置
                Class<?> type=field.getType();
                Object o= null;
                try {
    
    
                    o = type.newInstance();
                    field.set(userController,o);
                } catch (InstantiationException e) {
    
    
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
    
    
                    e.printStackTrace();
                }
            }
        });
        System.out.println(userController.getUserService());;
    }
}

猜你喜欢

转载自blog.csdn.net/a1773570500/article/details/125570440