Spring注解@Autowired可谓是我们每天必用,那你真的了解它的底层实现吗?今天通过一个简单的实例来模拟它的实现过程。
声明一个注解类一般使用我们底层的四个元注解,相关介绍可以参考:自定义注解
package test;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME) //表示注解的生命周期
@Target(ElementType.FIELD) //表示该注解用在属性上
@Documented //该注解将被包含在javaDoc中
@Inherited //子类可以继承父类中的注解
public @interface Autowired {
}
[1] 编写一个要被注入的类UserService.class
package test;
public class UserService {
}
[2] 编写一个使用@Autowired的业务类
(其中get方法是为了方便后面的检验)
package test;
public class UserController {
@Autowired
private UserService userService;
public UserService getUserService() {
return userService;
}
}
关键点就是通过反射获取出UserController类中属性的类型,并通过反射new出该对象,最终通过set把值设置到相应的对象中。
package test;
import java.lang.reflect.Field;
public class test {
public static void main(String[] args) throws Exception {
UserController userController = new UserController();
//1.获取相应类对象
Class<? extends UserController> clazz = userController.getClass();
//2.通过反射获取所有的属性
Field[] fields = clazz.getDeclaredFields();
for(Field f:fields) {
//3.获取标注了@Autowired注解的属性
Autowired annotation = f.getAnnotation(Autowired.class);
if(annotation!=null) {
//4.修改属性的权限值
f.setAccessible(true);
Class<?> type = f.getType(); //获取出相应的类型值
//5.new出相应类型的对象
Object o = type.newInstance();
//6.把值进行设置
f.set(userController, o);
}
}
System.out.println(userController.getUserService());
}
}