Spring IOC实现原理

IOC实现原理:反射

通过反射实现注入

  1. 创建UserService, UserController类

    public class UserController {
    
        private UserService userService;
    
        public UserService getUserService() {
            return userService;
        }
    }
    
    public class UserService {
    }
    
  2. 通过反射将UserService对象注入到UserController类的对象中

    public class IOC_01 {
    
        public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
            Class<? extends UserController> clazz = UserController.class;
            Field userServiceFiled = clazz.getDeclaredField("userService");
            userServiceFiled.setAccessible(true);
            UserController userController = (UserController) clazz.getConstructor().newInstance();
            UserService userService = new UserService();
            userServiceFiled.set(userController, userService);
            System.out.println(userController.getUserService() == userService);
        }
    
    }
    

加上注解

  1. 创建注解类AutoWried

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.FIELD)
    public @interface AutoWried {
        
        
    }
    
  2. 在UserController类加上注解

    public class UserController {
    
        @AutoWried
        private UserService userService;
    
        public UserService getUserService() {
            return userService;
        }
    }
    
  3. 先解析出被注解的属性,然后通过反射将UserService对象注入到UserController类的对象中

    public class IOC_02 {
    
        public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
            Class<? extends UserController> clazz = UserController.class;
            UserController userController = clazz.getConstructor().newInstance();
            Stream.of(clazz.getDeclaredFields()).forEach(field -> {
                AutoWried annotation = field.getAnnotation(AutoWried.class);
                if (annotation != null) {
                    field.setAccessible(true);
                    Class<?> declaringClass = field.getType();
                    try {
                        Object o = declaringClass.getConstructor().newInstance();
                        field.set(userController, o);
                        System.out.println(o);
                    } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                }
            });
            System.out.println(userController.getUserService());
        }
    
    }
    
上一篇:spring面试


下一篇:3.matplotlib介绍