反射实现Spring中的@Autowired注解

 1.整体思路

1.拿到运行时对象
2.拿到类中的所有属性值

3.判断属性值上面是否有自定义的autowired注解
4.获取属性对应的类
5.实例化对象
6.通过反射给运行时对象的属性赋值

 2.自定义注解

@Retention(value = RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Autowired {
}

3.整体实现 

public class UserService {
}

public class UserController {
    @Autowired
    private UserService userService;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
public class ReflectAutowiredImplements {
    @Test
    public void test() throws IllegalAccessException, InstantiationException {
        //Class controllerClass = UserController.class;
        //1.拿到运行时对象
        UserController userController = new UserController();
        Class controllerClass = userController.getClass();
        //2.拿到类中的所有属性值
        Field[] declaredFields = controllerClass.getDeclaredFields();
        for(Field f:declaredFields){
            f.setAccessible(true);
            //3.判断属性值上面是否有自定义的autowired注解
            Autowired annotation = f.getAnnotation(Autowired.class);
            if(null!=annotation){
                //4.获取属性对应的类
                Class type = f.getType();
                //5.实例化对象
                Object o = type.newInstance();
                //6.通过反射给运行时对象的属性赋值
                f.set(userController,o);
            }
        }
        System.out.println(userController.getUserService());
    }

}

 

 

你可能感兴趣的:(Spring)