每日一点涨薪小知识-手写Autowired

上期我们聊到了Java反射的一些基础知识,相信大家对于反射的基本用法应该有一定的了解了。本期我们使用Java反射的知识,手写一个Spring中的Autowired注解。
如果还有同学对Java反射不了解的,可以查看上期文章讲解。

每日一点涨薪小知识-JAVA反射

定义一个名为:Autowired的注解

package com.xuzhu.reflect;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author xuzhu
 * @date 2021/4/27
 * @desc
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Autowired {
}

定义一个service

package com.xuzhu.reflect;

/**
 * @author xuzhu
 * @date 2021/4/27
 * @desc
 */
public class PersonService {
}

定义一个controller

package com.xuzhu.reflect;

/**
 * @author xuzhu
 * @date 2021/4/27
 * @desc
 */
public class PersonController {

    @Autowired
    private PersonService personService;

    public PersonService getPersonService() {
        return personService;
    }

}

实现Autowired

package com.xuzhu.reflect;

import java.lang.reflect.Field;

/**
 * @author xuzhu
 * @date 2021/4/27
 * @desc
 */
public class TestAutowired {
    public static void main(String[] args) throws Exception {
        PersonController personController = new PersonController();
        Class<? extends PersonController> clazz = personController.getClass();
        //获取所有的属性值
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            String fieldName = field.getName();
            System.out.println("fieldName:" + fieldName);
            Autowired annotation = field.getAnnotation(Autowired.class);
            //判断当前属性是否有Autowired这个注解
            if (null != annotation) {
                //设置属性可以访问
                field.setAccessible(true);
                //获取属性类型
                Class<?> type = field.getType();
                //通过属性类型创建实例
                Object o = type.newInstance();
                //把创建好的实例对象设置到controller上
                field.set(personController, o);
            }
        }
        System.out.println(personController.getPersonService());
    }
}
// 打印结果
fieldName:personService
com.xuzhu.reflect.PersonService@63947c6b

是不是瞬间对Spring的Autowired理解通透了许多。不过这里仅仅把Autowired核心描述了一遍,具体Spring里面的一些细节操作将会在后续介绍。

微信公众号搜索【虚竹讲程序经】,关注不迷路,多敲代码,不掉头发,我们下期再见!

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值