300行代码手写Spring核心--Spring初探
目标:我们通过查看源码的方式一步步尝试完成springIOC容器的初始化 并完成dispatchServlet的功能
1.首先创建一个我们自己的Servlet并继承HttpServlet并重写init方法
public class EVServlet extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
super.init();
}
}
这一步和我们当初用servlet写web项目是一样的调用父类的init方法,我们这里显示地调用了父类的init无参方法,其实正常的servlet初始化是容器是调用含参init方法并在方法内部调用this.init(),并且this.config=config的,代码:
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
public void init() throws ServletException {
}
所以我们正常在重写父类的init含参方法时需要在一开始显示地调用父类的有参init方法,这样给 成员变量config赋了初值,在doget方法等内部随后才会获取,但是在我们这里只需要加载一次配置文件的类路径,后续不再需要,就不再显示地调用了
想一想spring当初完成dispatchServlet都是通过注解完成的,那么我们就要自己完成当初spring配置好的注解,并在初始化的时候把加了注解的类读取到内存然后并解析
2.我们创建自己的注解
(1)EVController
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EVController {
}
(2)EVRequestMapping
import java.lang.annotation.*;
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EVRequestMapping {
String value() default "";
}
(3)EVAutowired
import java.lang.annotation.*;
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EVAutowired {
String value() default "";
}
(4)EVRequestParam
import java.lang.annotation.*;
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EVRequestParam {
String value() default "";
}
(5)EVService
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EVService {
String value() default "";
}
3.我们的容器初始化需要那几个步骤呢?
@Override
public void init(ServletConfig config) throws ServletException {
//1.加载配置文件
doLoadConfig(config.getInitParameter("contextConfigLocation"));
//2.扫描相关的类
doScanner(contextConfig.getProperty("scanPackage"));
//3.始化扫描到的类,并且将它们放入到IOC容器之中
doInstance();
//4.完成依赖注入
doAutowired();
//5、初始化HandlerMapping
initHandlerMapping();
System.out.println("EV Spring framework is init.");
super.init();
}
分为五步,先根据我们配置文件定义的类扫描路径扫描包下带注解的类,放入IOC容器之中,然后完成依赖注入,并初始化HandlerMapping
4.配置文件
(1)web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Evan Web Application</display-name>
<servlet>
<servlet-name>evmvc</servlet-name>
<servlet-class>v2.servlet.EVServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>application.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>evmvc</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
(2)application.properties(就是初始化读取的那个配置文件)
因为只需要个类扫描路径,就是一句话
scanPackage=demo//我们一会儿在项目路径下创建个demo包,并把测试类写在下面
5.骨架搭建好开始填充内容
(0)先创建一些变量
//保存application.properties配置文件中的内容
private Properties contextConfig = new Properties();
//保存扫描的所有的类名
private List<String> classNames = new ArrayList<String>();
//传说中的IOC容器,我们来揭开它的神秘面纱
//为了简化程序,暂时不考虑ConcurrentHashMap
// 主要还是关注设计思想和原理
private Map<String,Object> ioc = new HashMap<String,Object>();
//保存url和Method的对应关系
// private Map<String,Method> handlerMapping = new HashMap<String,Method>();
//思考:为什么不用Map
//你用Map的话,key,只能是url
//Handler 本身的功能就是把url和method对应关系,已经具备了Map的功能
//根据设计原则:冗余的感觉了,单一职责,最少知道原则,帮助我们更好的理解
private List<Handler> handlerMapping = new ArrayList<Handler>();
(1)填充doLoadConfig方法
private void doLoadConfig(String contextConfigLocation) {
//直接从类路径下找到Spring主配置文件所在的路径
//并且将其读取出来放到Properties对象中
//相当于scanPackage=demo 从文件中保存到了内存中
InputStream fis = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
try {
//存放到Properties变量中
contextConfig.load(fis);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != fis) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ps:关于getResourceAsStream方法的作用请看我转载的另一篇文章:https://blog.csdn.net/qq_38762479/article/details/89226107,总之是默认从ClassPath根下获取资源,path不能以’/'开头,最终是由ClassLoader获取资源。
(2)填充doScanner方法
private void doScanner(String scanPackage) {
//把从配置文件中读取到的值转换为文件路径,实际上就是把.替换为/就OK了。
//我们这里路径只有一个demo没有.,但我们用的是properties文件如果路径再多一层是有点的
//classpath
URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
File classPath = new File(url.getFile());
for (File file : classPath.listFiles()) {
//如果是文件夹,递归
if (file.isDirectory()) {
doScanner(scanPackage + "." + file.getName());
} else {
//因为是类路径所以都以.class结尾
if (!file.getName().endsWith(".class")) {
continue;
}
String className = (scanPackage + "." + file.getName().replace(".class", ""));
//存放扫描到的类名
classNames.add(className);
}
}
}
在url上打一个断点给大家看一下:
大概就是这种效果了
(3)填充doInstance方法
private void doInstance() {
if (classNames.isEmpty()) {
return;
}
try {
for (String className : classNames) {
Class<?> clazz = Class.forName(className);
//什么样的类才需要初始化呢?
//加了注解的类,才初始化,怎么判断?
//为了简化代码逻辑,主要体会设计思想,只举例 @Controller和@Service,
// @Componment...就不一一举例了
if (clazz.isAnnotationPresent(EVController.class)) {
Object instance = clazz.newInstance();
//Spring默认类名首字母小写,方法写在下面
String beanName = toLowerFirstCase(clazz.getSimpleName());
ioc.put(beanName, instance);
} else if (clazz.isAnnotationPresent(EVService.class)) {
//1、自定义的beanName
EVService service = clazz.getAnnotation(EVService.class);
String beanName = service.value();
//2、默认类名首字母小写
if ("".equals(beanName.trim())) {
beanName = toLowerFirstCase(clazz.getSimpleName());
}
Object instance = clazz.newInstance();
ioc.put(beanName, instance);
//3、根据类型自动赋值,投机取巧的方式
for (Class<?> i : clazz.getInterfaces()) {
if (ioc.containsKey(i.getName())) {
throw new Exception("The “" + i.getName() + "” is exists!!");
}
//把接口的类型直接当成key了
ioc.put(i.getName(), instance);
}
} else {
continue;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
//如果类名本身是小写字母,确实会出问题
//但是我要说明的是:这个方法是我自己用,private的
//传值也是自己传,类也都遵循了驼峰命名法
//默认传入的值,存在首字母小写的情况,也不可能出现非字母的情况
//为了简化程序逻辑,就不做其他判断了,大家了解就OK
//其实用写注释的时间都能够把逻辑写完了
private String toLowerFirstCase(String simpleName) {
char[] chars = simpleName.toCharArray();
//之所以加,是因为大小写字母的ASCII码相差32,
// 而且大写字母的ASCII码要小于小写字母的ASCII码
//在Java中,对char做算学运算,实际上就是对ASCII码做算学运算
chars[0] += 32;
return String.valueOf(chars);
}
(4)填充Autowired
private void doAutowired() {
if (ioc.isEmpty()) {
return;
}
for (Map.Entry<String, Object> entry : ioc.entrySet()) {
//Declared 所有的,特定的 字段,包括private/protected/default
//正常来说,普通的OOP编程只能拿到public的属性
Field[] fields = entry.getValue().getClass().getDeclaredFields();
for (Field field : fields) {
if (!field.isAnnotationPresent(EVAutowired.class)) {
continue;
}
EVAutowired autowired = field.getAnnotation(EVAutowired.class);
//如果用户没有自定义beanName,默认就根据类型注入
//这个地方省去了对类名首字母小写的情况的判断
//小伙伴们自己去完善
String beanName = autowired.value().trim();
if ("".equals(beanName)) {
//获得接口的类型,作为key待会拿这个key到ioc容器中去取值
beanName = field.getType().getName();
}
//如果是public以外的修饰符,只要加了@Autowired注解,都要强制赋值
//反射中叫做暴力访问, 强吻
field.setAccessible(true);
try {
//用反射机制,动态给字段赋值
field.set(entry.getValue(), ioc.get(beanName));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
(5)填充initHandlerMapping
private void initHandlerMapping() {
if (ioc.isEmpty()) {
return;
}
for (Map.Entry<String, Object> entry : ioc.entrySet()) {
Class<?> clazz = entry.getValue().getClass();
if (!clazz.isAnnotationPresent(EVController.class)) {
continue;
}
//保存写在类上面的@EVRequestMapping("/demo")
String baseUrl = "";
if (clazz.isAnnotationPresent(EVRequestMapping.class)) {
EVRequestMapping requestMapping = clazz.getAnnotation(EVRequestMapping.class);
baseUrl = requestMapping.value();
}
//默认获取所有的public方法
for (Method method : clazz.getMethods()) {
if (!method.isAnnotationPresent(EVRequestMapping.class)) {
continue;
}
//方法上也可能有请求路径
EVRequestMapping requestMapping = method.getAnnotation(EVRequestMapping.class);
//优化
// //demo///query
String regex = ("/" + baseUrl + "/" + requestMapping.value())
.replaceAll("/+", "/");
Pattern pattern = Pattern.compile(regex);
this.handlerMapping.add(new Handler(pattern, entry.getValue(), method));
// handlerMapping.put(url,method);
System.out.println("Mapped :" + pattern + "," + method);
}
}
}
//保存一个url和一个Method的关系
public class Handler {
//必须把url放到HandlerMapping才好理解吧
private Pattern pattern; //正则
private Method method;
private Object controller;
private Class<?>[] paramTypes;
public Pattern getPattern() {
return pattern;
}
public Method getMethod() {
return method;
}
public Object getController() {
return controller;
}
public Class<?>[] getParamTypes() {
return paramTypes;
}
//形参列表
//参数的名字作为key,参数的顺序,位置作为值
private Map<String, Integer> paramIndexMapping;
public Handler(Pattern pattern, Object controller, Method method) {
this.pattern = pattern;
this.method = method;
this.controller = controller;
paramTypes = method.getParameterTypes();
paramIndexMapping = new HashMap<String, Integer>();
putParamIndexMapping(method);
}
private void putParamIndexMapping(Method method) {
//提取方法中加了注解的参数
//把方法上的注解拿到,得到的是一个二维数组
//因为一个参数可以有多个注解,而一个方法又有多个参数
Annotation[][] pa = method.getParameterAnnotations();
for (int i = 0; i < pa.length; i++) {
for (Annotation a : pa[i]) {
if (a instanceof EVRequestParam) {
String paramName = ((EVRequestParam) a).value();
if (!"".equals(paramName.trim())) {
paramIndexMapping.put(paramName, i);
}
}
}
}
//提取方法中的request和response参数
Class<?>[] paramsTypes = method.getParameterTypes();
for (int i = 0; i < paramsTypes.length; i++) {
Class<?> type = paramsTypes[i];
if (type == HttpServletRequest.class ||
type == HttpServletResponse.class) {
paramIndexMapping.put(type.getName(), i);
}
}
}
// private
}
这就完成容器的初始化
(6)dispatchServlet
然后要考虑如何把请求分发到我们已经储存的HanderlerMapping
private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
Handler handler = getHandler(req);
if (handler == null) {
// if(!this.handlerMapping.containsKey(url)){
resp.getWriter().write("404 Not Found!!!");
return;
}
//获得方法的形参列表
Class<?>[] paramTypes = handler.getParamTypes();
Object[] paramValues = new Object[paramTypes.length];
Map<String, String[]> params = req.getParameterMap();
for (Map.Entry<String, String[]> parm : params.entrySet()) {
String value = Arrays.toString(parm.getValue()).replaceAll("\\[|\\]", "")
.replaceAll("\\s", ",");
if (!handler.paramIndexMapping.containsKey(parm.getKey())) {
continue;
}
int index = handler.paramIndexMapping.get(parm.getKey());
paramValues[index] = convert(paramTypes[index], value);
}
if (handler.paramIndexMapping.containsKey(HttpServletRequest.class.getName())) {
int reqIndex = handler.paramIndexMapping.get(HttpServletRequest.class.getName());
paramValues[reqIndex] = req;
}
if (handler.paramIndexMapping.containsKey(HttpServletResponse.class.getName())) {
int respIndex = handler.paramIndexMapping.get(HttpServletResponse.class.getName());
paramValues[respIndex] = resp;
}
Object returnValue = handler.method.invoke(handler.controller, paramValues);
if (returnValue == null || returnValue instanceof Void) {
return;
}
resp.getWriter().write(returnValue.toString());
}
private Handler getHandler(HttpServletRequest req) {
if (handlerMapping.isEmpty()) {
return null;
}
//绝对路径
String url = req.getRequestURI();
//处理成相对路径
String contextPath = req.getContextPath();
url = url.replaceAll(contextPath, "").replaceAll("/+", "/");
for (Handler handler : this.handlerMapping) {
Matcher matcher = handler.getPattern().matcher(url);
if (!matcher.matches()) {
continue;
}
return handler;
}
return null;
}
(7)重写doGet和doPost方法
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//6、调用,运行阶段
try {
doDispatch(req, resp);
} catch (Exception e) {
e.printStackTrace();
resp.getWriter().write("500 Exection,Detail : " + Arrays.toString(e.getStackTrace()));
}
}
(8)写测试用例
1)接口
public interface IDemoService {
String get(String name);
}
2)实现Service
/**
* 核心业务逻辑
*/
@EVService
public class DemoService implements IDemoService {
public String get(String name) {
return "My name is " + name;
}
3)Controller
@EVController
@EVRequestMapping("/demo")
public class DemoAction {
@EVAutowired
private IDemoService demoService;
@EVRequestMapping("/query.*")
public void query(HttpServletRequest req, HttpServletResponse resp,
@EVRequestParam("name") String name){
// String result = demoService.get(name);
String result = "My name is " + name;
try {
resp.getWriter().write(result);
} catch (IOException e) {
e.printStackTrace();
}
}
@EVRequestMapping("/add")
public void add(HttpServletRequest req, HttpServletResponse resp,
@EVRequestParam("a") Integer a, @EVRequestParam("b") Integer b){
try {
resp.getWriter().write(a + "+" + b + "=" + (a + b));
} catch (IOException e) {
e.printStackTrace();
}
}
@EVRequestMapping("/sub")
public void add(HttpServletRequest req, HttpServletResponse resp,
@EVRequestParam("a") Double a, @EVRequestParam("b") Double b){
try {
resp.getWriter().write(a + "-" + b + "=" + (a - b));
} catch (IOException e) {
e.printStackTrace();
}
}
@EVRequestMapping("/remove")
public String remove(@EVRequestParam("id") Integer id){
return "" + id;
}
}
(9)运行结果截图