上期我们聊到了Java反射的一些基础知识,相信大家对于反射的基本用法应该有一定的了解了。本期我们使用Java反射的知识,手写一个Spring中的Autowired注解。
如果还有同学对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里面的一些细节操作将会在后续介绍。
微信公众号搜索【虚竹讲程序经】,关注不迷路,多敲代码,不掉头发,我们下期再见!