今天复习Spring,利用反射模拟了一下@Autowired功能。
- MyAutowired
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAutoWired { }
- Service
public class UserService { }
public class TeacherService { }
- Controller
public class UserController {
@MyAutoWired
private UserService userService;
@MyAutoWired
private TeacherService teacherService;
public UserService getUserService() {
return userService;
}
public TeacherService getTeacherService() {
return teacherService;
}
}
- Test
public class myTest {
@Test
public void test(){
UserController userController = new UserController();
Class<? extends UserController> clazz = userController.getClass();
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i <fields.length ; i++) {
MyAutoWired annotation = fields[i].getAnnotation(MyAutoWired.class);
if(annotation!=null){
fields[i].setAccessible(true);
Class<?> type = fields[i].getType();
try {
//生成注入的对象
Object o = type.newInstance();
//注入
fields[i].set(userController,o );
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
System.out.println(userController.getUserService());
System.out.println(userController.getTeacherService());
}
}
结果:
欢迎大家评论,如果本文对您有帮助,请点个赞,您的点赞对我很重要!这次一定!感谢!!!
转发请注明出处呦!感谢!!!