实现Spring autowired

太牛了!竟然真的有人能花700分钟把Spring+springboot源码给讲透彻了(真香)
首先,我们有这两个类

public class UserController {

    private UserService userService ;

    public UserService getUserService() {
        return userService;
    }

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

UserController类调用了UserService类但没有对其初始化,在spring中我们是通过@Autowired将UserService类这个类放入容器当中的,现在我们想手动实现了下@Autowired对应的功能,怎么做?答案是通过反射

@Test
public void test() throws NoSuchFieldException, IllegalAccessException {

    UserController userController = new UserController();
    Class<? extends UserController> aClass = userController.getClass();

    //getDeclaredFields():获得某个类的所有声明的字段,即包括public、private和proteced,但是不包括父类的申明字段。
    Field[] declaredFields = aClass.getDeclaredFields();
    for (int i = 0; i < declaredFields.length; i++) {
        System.out.println("declaredFields = "+declaredFields[i].getName());
    }

    System.out.println();

    Field[] fields = aClass.getFields();   //getFields():获得某个类的所有的公共(public)的字段,包括父类中的字段。
    for (int i = 0; i < fields.length; i++) {
        System.out.println("fields = "+fields[i].getName());
    }

    System.out.println("complete");

}

/*输出内容
declaredFields = userService

complete
*/
@Test
public void test2() throws Exception {

    UserController userController = new UserController();
    /*得到UserController的实例*/
    Class<? extends UserController> aClass = userController.getClass();

    /*得到UserService的实例*/
    UserService userService = new UserService();
    System.out.println("userService = " + userService);

    /*得到UserController的字段*/
    Field Filed = aClass.getDeclaredField("userService");
    Filed.setAccessible(true);   //可以访问私有属性的值

    /*得到字段名称*/
    String name = Filed.getName();
    System.out.println("name = " + name);

    /*处理字段名称*/
    name = name.substring(0,1).toUpperCase() + name.substring(1,name.length()) ;
    System.out.println("name = " + name);

    /*拼接字段名称*/
    String setMethodName = "set" + name ;
    System.out.println("setMethodName = " + setMethodName);

    /*得到拼接好的字段名称对应的方法*/
    Method method = aClass.getMethod(setMethodName, UserService.class);

    /*调用method的invoke方法  传递之前创建的userService对象*/
    method.invoke(userController , userService) ;
    System.out.println(userController.getUserService());


}

好了,现在我们可以开始定义我们自己的注解了

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Myautowired {
}
public class UserController {

    @Myautowired
    private UserService userService ;

    public UserService getUserService() {
        return userService;
    }

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

}
@Test
public void test(){
    UserController userController = new UserController();
    Class<? extends UserController> aClass = userController.getClass();
    // UserService userService = new UserService();
    /*获取所有的属性值*/
    Stream.of(aClass.getDeclaredFields()).forEach(
            field -> {
                String name = field.getName();
                Myautowired annotation = field.getAnnotation(Myautowired.class);
                if (annotation != null){
                    field.setAccessible(true);
                    Class<?> type = field.getType();  //获取属性的类型
                    try {
                        Object o = type.newInstance();  //new一个UserService的对象
                        field.set(userController,o);
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
    );
    System.out.println(userController.getUserService());
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值