Spring基础_手写实现Spring中的注解按类型注入@Autowired

62 阅读1分钟

手写实现Spring中的注解按类型注入@Autowired

思路:上一篇文章运用普通的反射,实现Spring的基本功能,这篇文章运用反射,实现spring的注解功能

UserController类

public class UserController {

@AutoWired
    private UserService userService;


   public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}

UserService类

public class UserService {
}

AutoWired接口

Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Inherited
@Documented
public @interface AutoWired {

}

MyTest2

public class MyTest2 {
    @Test
    public void test(){
        UserController userController=new UserController();
        Class<? extends UserController> clazz = userController.getClass();
//        UserService userService = new UserService();

        //获取所有属性值
        Stream.of(clazz.getDeclaredFields()).forEach(field->{
            String name=field.getName();
            AutoWired annotation = field.getAnnotation(AutoWired.class);
            if (annotation!=null){
                field.setAccessible(true);
                //获取属性类型
                Class<?> type = field.getType();

                try {
                    Object o = type.newInstance();
                    field.set(userController,o);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println(userController.getUserService());
    }
}

结果

com.mashibing.reflect.service.UserService@606d8acf