手写实现Spring IoC Autowired
MyAutowired注解类
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAutowired {
}
UserController控制器类
public class UserController {
@MyAutowired
private UserService userService;
public String getUserName() {
return userService.getUserName();
}
}
UserService服务类
public class UserService {
public String getUserName() {
return "abc";
}
}
TestMyAutowired测试类
import org.junit.Test;
import java.lang.reflect.Field;
import static org.junit.Assert.assertEquals;
public class TestMyAutowired {
@Test
public void test() {
UserController userController = new UserController();
// 获取Class对象
Class clazz = userController.getClass();
// 遍历userController的所有属性
for (Field field : clazz.getDeclaredFields()) {
// 确认属性是否有MyAutowired注解
MyAutowired annotation = field.getAnnotation(MyAutowired.class);
if (annotation == null) {
continue;
}
// 允许访问私有属性
field.setAccessible(true);
// 获取属性的类型
Class type = field.getType();
try {
// 创建MyAutowired注解修饰的对象
Object o = type.newInstance();
// 把对象注入到MyAutowired注解修饰的属性
field.set(userController, o);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
assertEquals(userController.getUserName(), "abc");
}
}
参考资料
实现Spring autowired
https://blog.csdn.net/qq_30763385/article/details/108969883