手写Spring的Autowired注解
定义Autowired
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Inherited
@Documented
public @interface Autowired {
}
定义UserService
public class UserService {}
定义UserController
public class UserController {
@Autowired // 这里的注解使用我们自己申明的
private UserService userService;
public UserService getUserService() {
return userService;
}
}
定义测试函数
UserController userController = new UserController();
Class<? extends UserController> clazz = userController.getClass();
// 获取所有属性
Stream.of(clazz.getDeclaredFields()).forEach(field -> {
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());
本来UserController中的userServic对应的是null,经过函数运行后,就赋值了进去。