我们学完Spring后,大都就直接接着学习之后的内容啦,但是我想偶尔回过头来看一看,才能走的更远啊。
温故而知新。
关于Spring是怎么实现的?怎么我写了一个注解就可以直接注入了?
这种问题,我开始学的时候就好奇了,当时懂的比较少,查完也就给忘记了。
随着学的越来越多,就越来越感觉到基础的重要性,所以就想再抽空来复习一遍。
本文写的是一个小demo,并不是从Spring的架构去谈Spring。
只对Spring的ioc的注入用java的反射做了一个简单的理解。
我想可以满足许多同我一样产生过好奇心的同学一个满足。
全部代码都可以直接copy测试,仅仅导入了junit。其余都是使用jdk反射实现的。
首先写一个类 UserService
/**
* @Author: crush
* @Date: 2021-05-27 10:36
* version 1.0
*/
public class UserService {
public void test(){
System.out.println("这是一个测试!!!");
}
}再像Spring一样 来写个注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Author: crush
* @Date: 2021-05-27 10:36
* version 1.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AutoWired {
}接着 写一个UserController
/**
* @Author: crush
* @Date: 2021-05-27 10:36
* version 1.0
*/
public class UserController {
@AutoWired
private UserService userService;
public UserService getUserService() {
return userService;
}
public void test(){
userService.test();
}
}最后的就是测试
import org.junit.Test;
import java.util.stream.Stream;
/**
* @Author: crush
* @Date: 2021-05-27 10:40
* version 1.0
*/
public class MyTest {
@Test
public void iocTest() {
UserController userController = new UserController();
Class<? extends UserController> clazz = userController.getClass();
// 获取所有属性值
Stream.of(clazz.getDeclaredFields()).forEach(field -> {
String name = field.getName();
AutoWired annotation = field.getAnnotation(AutoWired.class);
if (annotation != null) {
// 防止私有属性 也称暴力反射
field.setAccessible(true);
// 获取属性的类型
Class<?> type = field.getType();
try {
//创建此Class对象表示的类的新实例。 就像通过带有空参数列表的new表达式实例化该类一样。
// 如果尚未初始化该类,则将其初始化。
Object o = type.newInstance();
field.set(userController,o);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
});
// 这里是测试
System.out.println(userController.getUserService());
userController.test();
}
}
我觉得Spring真的很多,看到都会产生一种恐惧,最近在对Spring进行深一步的了解,会接着发博客。
可是就是因为人对世间事物的好奇,才能走的更远吧,我已经感觉对Spring产生极大的兴趣啦。
大家一起加油哦