17.用300行代码手写初体验Spring V1.0版本

2024-06-24 13:48

本文主要是介绍17.用300行代码手写初体验Spring V1.0版本,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.1.课程目标

1、了解看源码最有效的方式,先猜测后验证,不要一开始就去调试代码。

2、浓缩就是精华,用 300行最简洁的代码

提炼Spring的基本设计思想。

3、掌握Spring框架的基本脉络。

1.2.内容定位

1、 具有1年以上的SpringMVC使用经验。

2、 希望深入了解Spring源码的人群,对 Spring有一个整体的宏观感受。

3、 全程手写实现SpringMVC的核心功能,从最简单的V1版本一步一步优化为V2版本,最后到V3版本。

1.3.实现思路

先来介绍一下Mini版本的Spring基本实现思路,如下图所示:

image-20200331202948382

1.4.自定义配置 application.properties 文件

为了解析方便,我们用application.properties来代替application.xml文 件 ,具体配置内容如下:

scanPackage=com.gupaoedu.demo

1.5.配置web.xml文件

大家都知道,所有依赖于web容器的项目,都是从读取web.xml文件开始的。我们先配置好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>Gupao Web Application</display-name><servlet><servlet-name>gpmvc</servlet-name><servlet-class>com.gupaoedu.mvcframework.v2.servlet.GPDispatchServlet</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>gpmvc</servlet-name><url-pattern>/*</url-pattern></servlet-mapping>
</web-app>

其中GPDispatcherServlet是有自己模拟Spring实现的核心功能类。

1.6.自定义 Annotation

@GPService 注解:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface GPService {String value() default "";
}

@GPAutowired 注 解 :

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface GPAutowired {String value() default "";
}

@GPController 注 解 :

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface GPController {String value() default "";
}

@GPRequestMapping 注 解 :

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface GPRequestMapping {String value() default "";
}

@GPRequestParam 注 解 :

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface GPRequestParam {String value() default "";
}

1.7.配置 Annotation

配置业务实现类DemoService :

/*** 核心业务逻辑*/
@GPService
public class DemoService implements IDemoService{public String get(String name) {return "My name is " + name + ",from service.";}}

配置请求入口类DemoAction :

//虽然,用法一样,但是没有功能
@GPController
@GPRequestMapping("/demo")
public class DemoAction {@GPAutowired private IDemoService demoService;@GPRequestMapping("/query")public void query(HttpServletRequest req, HttpServletResponse resp,@GPRequestParam("name") String name){String result = demoService.get(name);// String result = "My name is " + name;try {resp.getWriter().write(result);} catch (IOException e) {e.printStackTrace();}}@GPRequestMapping("/add")public void add(HttpServletRequest req, HttpServletResponse resp,@GPRequestParam("a") Integer a, @GPRequestParam("b") Integer b){try {resp.getWriter().write(a + "+" + b + "=" + (a + b));} catch (IOException e) {e.printStackTrace();}}@GPRequestMapping("/sub")public void add(HttpServletRequest req, HttpServletResponse resp,@GPRequestParam("a") Double a, @GPRequestParam("b") Double b){try {resp.getWriter().write(a + "-" + b + "=" + (a - b));} catch (IOException e) {e.printStackTrace();}}@GPRequestMapping("/remove")public String  remove(@GPRequestParam("id") Integer id){return "" + id;}}

至 此 ,配置阶段就已经完成。

1.8.容器初始化实现V1版本

所有的核心逻辑全部写在一个init()方法中。

public class GPDispatcherServlet extends HttpServlet {private Map<String,Object> mapping = new HashMap<String, Object>();@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doPost(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {try {doDispatch(req,resp);} catch (Exception e) {resp.getWriter().write("500 Exception " + Arrays.toString(e.getStackTrace()));}}private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {String url = req.getRequestURI();String contextPath = req.getContextPath();url = url.replace(contextPath, "").replaceAll("/+", "/");if(!this.mapping.containsKey(url)){resp.getWriter().write("404 Not Found!!");return;}Method method = (Method) this.mapping.get(url);Map<String,String[]> params = req.getParameterMap();method.invoke(this.mapping.get(method.getDeclaringClass().getName()),new Object[]{req,resp,params.get("name")[0]});}//init方法肯定干得的初始化的工作//inti首先我得初始化所有的相关的类,IOC容器、servletBean@Overridepublic void init(ServletConfig config) throws ServletException {InputStream is = null;try{Properties configContext = new Properties();is = this.getClass().getClassLoader().getResourceAsStream(config.getInitParameter("contextConfigLocation"));configContext.load(is);String scanPackage = configContext.getProperty("scanPackage");doScanner(scanPackage);for (String className : mapping.keySet()) {if(!className.contains(".")){continue;}Class<?> clazz = Class.forName(className);if(clazz.isAnnotationPresent(GPController.class)){mapping.put(className,clazz.newInstance());String baseUrl = "";if (clazz.isAnnotationPresent(GPRequestMapping.class)) {GPRequestMapping requestMapping = clazz.getAnnotation(GPRequestMapping.class);baseUrl = requestMapping.value();}Method[] methods = clazz.getMethods();for (Method method : methods) {if (!method.isAnnotationPresent(GPRequestMapping.class)) {  continue; }GPRequestMapping requestMapping = method.getAnnotation(GPRequestMapping.class);String url = (baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");mapping.put(url, method);System.out.println("Mapped " + url + "," + method);}}else if(clazz.isAnnotationPresent(GPService.class)){GPService service = clazz.getAnnotation(GPService.class);String beanName = service.value();if("".equals(beanName)){beanName = clazz.getName();}Object instance = clazz.newInstance();mapping.put(beanName,instance);for (Class<?> i : clazz.getInterfaces()) {mapping.put(i.getName(),instance);}}else {continue;}}for (Object object : mapping.values()) {if(object == null){continue;}Class clazz = object.getClass();if(clazz.isAnnotationPresent(GPController.class)){Field [] fields = clazz.getDeclaredFields();for (Field field : fields) {if(!field.isAnnotationPresent(GPAutowired.class)){continue; }GPAutowired autowired = field.getAnnotation(GPAutowired.class);String beanName = autowired.value();if("".equals(beanName)){beanName = field.getType().getName();}field.setAccessible(true);try {field.set(mapping.get(clazz.getName()),mapping.get(beanName));} catch (IllegalAccessException e) {e.printStackTrace();}}}}} catch (Exception e) {}finally {if(is != null){try {is.close();} catch (IOException e) {e.printStackTrace();}}}System.out.print("GP MVC Framework is init");}private void doScanner(String scanPackage) {URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.","/"));File classDir = new File(url.getFile());for (File file : classDir.listFiles()) {if(file.isDirectory()){ doScanner(scanPackage + "." +  file.getName());}else {if(!file.getName().endsWith(".class")){continue;}String clazzName = (scanPackage + "." + file.getName().replace(".class",""));mapping.put(clazzName,null);}}}
}

1.9.实现V2版本

在 V1版本上进了优化,采用了常用的设计模式(工厂模式、单例模式、委派模式、策略模式),将 inito方法中的代 码进行封装。按照之前的实现思路,先搭基础框架,再填肉注血,具体代码如下:

//初始化阶段
@Override
public void init(ServletConfig config) throws ServletException {//1、加载配置文件doLoadConfig(config.getInitParameter("contextConfigLocation"));//2、扫描相关的类doScanner(contextConfig.getProperty("scanPackage"));//3、初始化扫描到的类,并且将它们放入到ICO容器之中doInstance();//4、完成依赖注入doAutowired();//5、初始化HandlerMappinginitHandlerMapping();System.out.println("GP Spring framework is init.");
}

声明全局的成员变量,其中IOC容器就是注册时单例的具体案例:

//保存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>();

实现 doLoadConfig方法:

//加载配置文件
private void doLoadConfig(String contextConfigLocation) {//直接从类路径下找到Spring主配置文件所在的路径//并且将其读取出来放到Properties对象中//相对于scanPackage=com.gupaoedu.demo 从文件中保存到了内存中InputStream fis = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);try {contextConfig.load(fis);} catch (IOException e) {e.printStackTrace();}finally {if(null != fis){try {fis.close();} catch (IOException e) {e.printStackTrace();}}}
}

实现doScanner()方 法 :

//扫描出相关的类
private void doScanner(String scanPackage) {//scanPackage = com.gupaoedu.demo ,存储的是包路径//转换为文件路径,实际上就是把.替换为/就OK了//classpathURL 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{if(!file.getName().endsWith(".class")){ continue;}String className = (scanPackage + "." + file.getName().replace(".class",""));classNames.add(className);}}
}

实现dolnstance()方法,dolnstance。方法就是工厂模式的具体实现:

private void doInstance() {//初始化,为DI做准备if(classNames.isEmpty()){return;}try {for (String className : classNames) {Class<?> clazz = Class.forName(className);//什么样的类才需要初始化呢?//加了注解的类,才初始化,怎么判断?//为了简化代码逻辑,主要体会设计思想,只举例 @Controller和@Service,// @Componment...就一一举例了if(clazz.isAnnotationPresent(GPController.class)){Object instance = clazz.newInstance();//Spring默认类名首字母小写String beanName = toLowerFirstCase(clazz.getSimpleName());ioc.put(beanName,instance);}else if(clazz.isAnnotationPresent(GPService.class)){//1、自定义的beanNameGPService service = clazz.getAnnotation(GPService.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();}}

为了处理方便,自己实现了 toLowerFirstCase方法,来实现类名首字母小写,具体代码如下:

//如果类名本身是小写字母,确实会出问题
//但是我要说明的是:这个方法是我自己用,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);
}

实现 doAutowired方法:

//自动依赖注入
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(GPAutowired.class)){continue;}GPAutowired autowired = field.getAnnotation(GPAutowired.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();}}}
}

实现dolnitHandlerMapping方法,handlerMapping就是策略模式的应用案例:

//初始化url和Method的一对一对应关系
private void initHandlerMapping() {if(ioc.isEmpty()){ return; }for (Map.Entry<String, Object> entry : ioc.entrySet()) {Class<?> clazz = entry.getValue().getClass();if(!clazz.isAnnotationPresent(GPController.class)){continue;}//保存写在类上面的@GPRequestMapping("/demo")String baseUrl = "";if(clazz.isAnnotationPresent(GPRequestMapping.class)){GPRequestMapping requestMapping = clazz.getAnnotation(GPRequestMapping.class);baseUrl = requestMapping.value();}//默认获取所有的public方法for (Method method : clazz.getMethods()) {if(!method.isAnnotationPresent(GPRequestMapping.class)){continue;}GPRequestMapping requestMapping = method.getAnnotation(GPRequestMapping.class);//优化// //demo///queryString url = ("/" + baseUrl + "/" + requestMapping.value()).replaceAll("/+","/");handlerMapping.put(url,method);System.out.println("Mapped :" + url + "," + method);}}
}

到这里位置初始化阶段就已经完成,接下实现运行阶段的逻辑,来看doPost/doGet的代码:

@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()));}}

doPost()方法中,用了委派模式,委派模式的具体逻辑在doDispatch方法中:

private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {String url = req.getRequestURI();String contextPath = req.getContextPath();url = url.replace(contextPath, "").replaceAll("/+", "/");if(!this.mapping.containsKey(url)){resp.getWriter().write("404 Not Found!!");return;}Method method = (Method) this.mapping.get(url);Map<String,String[]> params = req.getParameterMap();method.invoke(this.mapping.get(method.getDeclaringClass().getName()),new Object[]{req,resp,params.get("name")[0]});
}

在以上代码中,doDispatch。虽然完成了动态委派并反射调用,但对url参数处理还是静态代码。
的动态获E
要实现url参数
,其实还稍微有些复杂。我们可以优化doDispatch方法的实现逻辑,代码如下:

private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {//绝对路径String url = req.getRequestURI();//处理成相对路径String contextPath = req.getContextPath();url = url.replaceAll(contextPath,"").replaceAll("/+","/");if(!this.handlerMapping.containsKey(url)){resp.getWriter().write("404 Not Found!!!");return;}Method method = this.handlerMapping.get(url);//从reqest中拿到url传过来的参数Map<String,String[]> params = req.getParameterMap();//获取方法的形参列表Class<?> [] parameterTypes = method.getParameterTypes();Object [] paramValues = new Object[parameterTypes.length];for (int i = 0; i < parameterTypes.length; i ++) {Class parameterType = parameterTypes[i];//不能用instanceof,parameterType它不是实参,而是形参if(parameterType == HttpServletRequest.class){paramValues[i] = req;continue;}else if(parameterType == HttpServletResponse.class){paramValues[i] = resp;continue;}else if(parameterType == String.class){GPRequestParam requestParam = (GPRequestParam)parameterType.getAnnotation(GPRequestParam.class);if(params.containsKey(requestParam.value())) {for (Map.Entry<String,String[]> param : params.entrySet()){String value = Arrays.toString(param.getValue()).replaceAll("\\[|\\]","").replaceAll("\\s",",");paramValues[i] = value;}}}}//投机取巧的方式//通过反射拿到method所在class,拿到class之后还是拿到class的名称//再调用toLowerFirstCase获得beanNameString beanName  = toLowerFirstCase(method.getDeclaringClass().getSimpleName());method.invoke(ioc.get(beanName),paramValues);
}

1.10.实现V3版本

在 V2版本中,基本功能以及完全实现,但代码的优雅程度还不如人意。譬如HandlerMapping还不能像SpringMVC 一样支持正则,url参数还不支持强制类型转换,在反射调用前还需要重新获取beanName ,在V3版本中,下面我们
继续优化。

首先,改造HandlerMapping , 在真实的Spring源码中,HandlerMapping其实是一个List而非Mapo List中的元
素是一个自定义的类型。现在我们来仿真写一段代码,先定义一个内部类Handler类 :

//保存一个url和一个Method的关系
private 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 GPRequestParam){String paramName = ((GPRequestParam) 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);}}}
}

然后,优化HandlerMapping的结构,代码如下:

//保存所有的URL和方法的映射关系
private List<Handler> handlerMapping = new ArrayList<Handler>();

修改 dolnitHandlerMapping方 法 :

//初始化url和Method的一对一对应关系
private void initHandlerMapping() {if(ioc.isEmpty()){ return; }for (Map.Entry<String, Object> entry : ioc.entrySet()) {Class<?> clazz = entry.getValue().getClass();if(!clazz.isAnnotationPresent(GPController.class)){continue;}//保存写在类上面的@GPRequestMapping("/demo")String baseUrl = "";if(clazz.isAnnotationPresent(GPRequestMapping.class)){GPRequestMapping requestMapping = clazz.getAnnotation(GPRequestMapping.class);baseUrl = requestMapping.value();}//默认获取所有的public方法for (Method method : clazz.getMethods()) {if(!method.isAnnotationPresent(GPRequestMapping.class)){continue;}GPRequestMapping requestMapping = method.getAnnotation(GPRequestMapping.class);//优化// //demo///queryString regex = ("/" + baseUrl + "/" + requestMapping.value()).replaceAll("/+","/");Pattern pattern = Pattern.compile(regex);this.handlerMapping.add(new Handler(pattern,entry.getValue(),method));System.out.println("Mapped :" + pattern + "," + method);}}
}

修改 doDispatch()方法:

private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {Handler handler = getHandler(req);if (handler == null) {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;
}//url传过来的参数都是String类型的,HTTP是基于字符串协议
//只需要把String转换为任意类型就好
private Object convert(Class<?> type, String value) {//如果是intif (Integer.class == type) {return Integer.valueOf(value);} else if (Double.class == type) {return Double.valueOf(value);}//如果还有double或者其他类型,继续加if//这时候,我们应该想到策略模式了//在这里暂时不实现,希望小伙伴自己来实现return value;
}

在以上代码中,增加了两个方法,一个是getHandler。方法,主要负责处理url的正则匹配;一个是 convert()方 法 ,主要负责url参数的强制类型转换。

至此,手写Mini版 SpringMVC框架就已全部完成。

1.11.运行效果演示

在浏览器输入:http://localhost:8080/demo/query.json?name=Tom , 就会得到下面的结果:

image-20200331212455132

当然,真正的Spring要复杂很多,本课中主要通过手写的形式,了解Spring的基本设计思路以及设计 模式如何应用,在以后的课程中,我们还会继续手写更加高仿真版本的Spring2.0。

1.12.作业

1、请用自己的语言描述Spring IOC、DI、MVC的基本执行原理。

IOC:调用init()方法加载配置文件。IOC容器初始化,Map<String, Object>。扫描相关的类,scan-package = “com.gupaoedu”。创建实例化并保存至容器,通过反射机制将类实例化放入IOC容器中。

DI:进行DI操作,扫描IOC容器中的实例,给没有赋值的属性自动赋值。

MVC:初始化HandlerMapping,将一个URL和一个Method进行一对一的关系映射到Map<String, Method>。

2、Spring中的Bean是线程安全的吗?为什么?

  • Spring框架并没有对单例的bean进行多线程的封装处理,线程安全问题和并发问题,需要我们开发者自己考虑。
  • 但实际上,大部分的Spring bean并没有可变的状态(比如:service类和dao类),所有在某种程度上来说Spring单例bean是线程安全的。如果bean有多种状态的话(比如:View Model对象),就需要自行考虑线程安全问题。

参考资料:

1.《spring 5核心原理与30个类手写实战》谭勇德著

这篇关于17.用300行代码手写初体验Spring V1.0版本的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1090324

相关文章

Java五子棋之坐标校正

上篇针对了Java项目中的解构思维,在这篇内容中我们不妨从整体项目中拆解拿出一个非常重要的五子棋逻辑实现:坐标校正,我们如何使漫无目的鼠标点击变得有序化和可控化呢? 目录 一、从鼠标监听到获取坐标 1.MouseListener和MouseAdapter 2.mousePressed方法 二、坐标校正的具体实现方法 1.关于fillOval方法 2.坐标获取 3.坐标转换 4.坐

Spring Cloud:构建分布式系统的利器

引言 在当今的云计算和微服务架构时代,构建高效、可靠的分布式系统成为软件开发的重要任务。Spring Cloud 提供了一套完整的解决方案,帮助开发者快速构建分布式系统中的一些常见模式(例如配置管理、服务发现、断路器等)。本文将探讨 Spring Cloud 的定义、核心组件、应用场景以及未来的发展趋势。 什么是 Spring Cloud Spring Cloud 是一个基于 Spring

Javascript高级程序设计(第四版)--学习记录之变量、内存

原始值与引用值 原始值:简单的数据即基础数据类型,按值访问。 引用值:由多个值构成的对象即复杂数据类型,按引用访问。 动态属性 对于引用值而言,可以随时添加、修改和删除其属性和方法。 let person = new Object();person.name = 'Jason';person.age = 42;console.log(person.name,person.age);//'J

java8的新特性之一(Java Lambda表达式)

1:Java8的新特性 Lambda 表达式: 允许以更简洁的方式表示匿名函数(或称为闭包)。可以将Lambda表达式作为参数传递给方法或赋值给函数式接口类型的变量。 Stream API: 提供了一种处理集合数据的流式处理方式,支持函数式编程风格。 允许以声明性方式处理数据集合(如List、Set等)。提供了一系列操作,如map、filter、reduce等,以支持复杂的查询和转

uniapp接入微信小程序原生代码配置方案(优化版)

uniapp项目需要把微信小程序原生语法的功能代码嵌套过来,无需把原生代码转换为uniapp,可以配置拷贝的方式集成过来 1、拷贝代码包到src目录 2、vue.config.js中配置原生代码包直接拷贝到编译目录中 3、pages.json中配置分包目录,原生入口组件的路径 4、manifest.json中配置分包,使用原生组件 5、需要把原生代码包里的页面修改成组件的方

Java面试八股之怎么通过Java程序判断JVM是32位还是64位

怎么通过Java程序判断JVM是32位还是64位 可以通过Java程序内部检查系统属性来判断当前运行的JVM是32位还是64位。以下是一个简单的方法: public class JvmBitCheck {public static void main(String[] args) {String arch = System.getProperty("os.arch");String dataM

详细分析Springmvc中的@ModelAttribute基本知识(附Demo)

目录 前言1. 注解用法1.1 方法参数1.2 方法1.3 类 2. 注解场景2.1 表单参数2.2 AJAX请求2.3 文件上传 3. 实战4. 总结 前言 将请求参数绑定到模型对象上,或者在请求处理之前添加模型属性 可以在方法参数、方法或者类上使用 一般适用这几种场景: 表单处理:通过 @ModelAttribute 将表单数据绑定到模型对象上预处理逻辑:在请求处理之前

eclipse运行springboot项目,找不到主类

解决办法尝试了很多种,下载sts压缩包行不通。最后解决办法如图: help--->Eclipse Marketplace--->Popular--->找到Spring Tools 3---->Installed。

JAVA读取MongoDB中的二进制图片并显示在页面上

1:Jsp页面: <td><img src="${ctx}/mongoImg/show"></td> 2:xml配置: <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001

Java面试题:通过实例说明内连接、左外连接和右外连接的区别

在 SQL 中,连接(JOIN)用于在多个表之间组合行。最常用的连接类型是内连接(INNER JOIN)、左外连接(LEFT OUTER JOIN)和右外连接(RIGHT OUTER JOIN)。它们的主要区别在于它们如何处理表之间的匹配和不匹配行。下面是每种连接的详细说明和示例。 表示例 假设有两个表:Customers 和 Orders。 Customers CustomerIDCus