執行緒的建立方式以及synchronize的使用
阿新 • • 發佈:2020-07-02
續接前文
手寫SpringMVC框架(二)結構開發設計
本節我們來開始具體方法的程式碼實現。
doLoadConfig()方法的開發
思路:我們需要將contextConfigLocation路徑讀取過來的配置檔案springmvc.properties載入到記憶體中來。
實現:使用properties及類載入器。
程式碼如下:
import java.io.InputStream; import java.util.Properties; private Properties properties=new Properties(); //載入配置檔案 private void doLoadConfig(String contextConfigLocation) { InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation); try { properties.load(resourceAsStream); } catch (IOException e) { e.printStackTrace(); } }
doScan()掃描包方法的實現
程式碼如下:
List<String> classNames=new ArrayList<>(); //掃描類 磁碟上的資料夾及檔案 private void doScan(String scanPackage) { String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); File pack=new File(scanPackagePath); File[] files = pack.listFiles(); for (File file : files) { if (file.isDirectory()) { //遞迴 doScan(scanPackage+"."+file.getName()); //比如com.lagou.controller }else if(file.getName().endsWith(".class")){ String className = scanPackage + "." + file.getName().replaceAll(".class", ""); classNames.add(className); } } }
doInstance()方法:IOC例項化容器
程式碼如下
// ioc容器 private Map<String,Object> ioc = new HashMap<String,Object>(); // ioc容器 // 基於classNames快取的類的全限定類名,以及反射技術,完成物件建立和管理 private void doInstance() { if(classNames.size() == 0) return; try{ for (int i = 0; i < classNames.size(); i++) { String className = classNames.get(i); // com.lagou.demo.controller.DemoController // 反射 Class<?> aClass = Class.forName(className); // 區分controller,區分service' if(aClass.isAnnotationPresent(LagouController.class)) { // controller的id此處不做過多處理,不取value了,就拿類的首字母小寫作為id,儲存到ioc中 String simpleName = aClass.getSimpleName();// DemoController String lowerFirstSimpleName = lowerFirst(simpleName); // demoController Object o = aClass.newInstance(); ioc.put(lowerFirstSimpleName,o); }else if(aClass.isAnnotationPresent(LagouService.class)) { LagouService annotation = aClass.getAnnotation(LagouService.class); //獲取註解value值 String beanName = annotation.value(); // 如果指定了id,就以指定的為準 if(!"".equals(beanName.trim())) { ioc.put(beanName,aClass.newInstance()); }else{ // 如果沒有指定,就以類名首字母小寫 beanName = lowerFirst(aClass.getSimpleName()); ioc.put(beanName,aClass.newInstance()); } // service層往往是有介面的,面向介面開發,此時再以介面名為id,放入一份物件到ioc中,便於後期根據介面型別注入 Class<?>[] interfaces = aClass.getInterfaces(); for (int j = 0; j < interfaces.length; j++) { Class<?> anInterface = interfaces[j]; // 以介面的全限定類名作為id放入 ioc.put(anInterface.getName(),aClass.newInstance()); } }else{ continue; } } }catch (Exception e) { e.printStackTrace(); } } // 首字母小寫方法 public String lowerFirst(String str) { char[] chars = str.toCharArray(); if('A' <= chars[0] && chars[0] <= 'Z') { chars[0] += 32; } return String.valueOf(chars); }
doAutoWired()依賴注入:
// 實現依賴注入
private void doAutoWired() {
if(ioc.isEmpty()) {return;}
// 有物件,再進行依賴注入處理
// 遍歷ioc中所有物件,檢視物件中的欄位,是否有@LagouAutowired註解,如果有需要維護依賴注入關係
for(Map.Entry<String,Object> entry: ioc.entrySet()) {
// 獲取bean物件中的欄位資訊
Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
// 遍歷判斷處理
for (int i = 0; i < declaredFields.length; i++) {
Field declaredField = declaredFields[i]; // @LagouAutowired private IDemoService demoService;
if(!declaredField.isAnnotationPresent(LagouAutowired.class)) {
continue;
}
// 有該註解
LagouAutowired annotation = declaredField.getAnnotation(LagouAutowired.class);
String beanName = annotation.value(); // 需要注入的bean的id
if("".equals(beanName.trim())) {
// 沒有配置具體的bean id,那就需要根據當前欄位型別注入(介面注入) IDemoService
beanName = declaredField.getType().getName();
}
// 開啟賦值
declaredField.setAccessible(true);
try {
declaredField.set(entry.getValue(),ioc.get(beanName));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
相關pojo實體類
package com.lagou.edu.mvcframework.pojo;
import javax.sound.midi.MetaEventListener;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
/**
* 封裝handler方法相關的資訊
*/
public class Handler {
private Object controller; // method.invoke(obj,)
private Method method;
private Pattern pattern; // spring中url是支援正則的
private Map<String,Integer> paramIndexMapping; // 引數順序,是為了進行引數繫結,key是引數名,value代表是第幾個引數 <name,2>
public Handler(Object controller, Method method, Pattern pattern) {
this.controller = controller;
this.method = method;
this.pattern = pattern;
this.paramIndexMapping = new HashMap<>();
}
public Object getController() {
return controller;
}
public void setController(Object controller) {
this.controller = controller;
}
public Method getMethod() {
return method;
}
public void setMethod(Method method) {
this.method = method;
}
public Pattern getPattern() {
return pattern;
}
public void setPattern(Pattern pattern) {
this.pattern = pattern;
}
public Map<String, Integer> getParamIndexMapping() {
return paramIndexMapping;
}
public void setParamIndexMapping(Map<String, Integer> paramIndexMapping) {
this.paramIndexMapping = paramIndexMapping;
}
}
LgDispatcherServlet裡面的initHandleMapping()方法:
private List<Handler> handlerMapping = new ArrayList<>();
/*
構造一個HandlerMapping處理器對映器
最關鍵的環節
目的:將url和method建立關聯
*/
private void initHandlerMapping() {
if(ioc.isEmpty()) {return;}
for(Map.Entry<String,Object> entry: ioc.entrySet()) {
// 獲取ioc中當前遍歷的物件的class型別
Class<?> aClass = entry.getValue().getClass();
if(!aClass.isAnnotationPresent(LagouController.class)) {continue;}
String baseUrl = "";
if(aClass.isAnnotationPresent(LagouRequestMapping.class)) {
LagouRequestMapping annotation = aClass.getAnnotation(LagouRequestMapping.class);
baseUrl = annotation.value(); // 等同於/demo
}
// 獲取方法
Method[] methods = aClass.getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
// 方法沒有標識LagouRequestMapping,就不處理
if(!method.isAnnotationPresent(LagouRequestMapping.class)) {continue;}
// 如果標識,就處理
LagouRequestMapping annotation = method.getAnnotation(LagouRequestMapping.class);
String methodUrl = annotation.value(); // /query
String url = baseUrl + methodUrl; // 計算出來的url /demo/query
// 把method所有資訊及url封裝為一個Handler
Handler handler = new Handler(entry.getValue(),method, Pattern.compile(url));
// 計算方法的引數位置資訊 // query(HttpServletRequest request, HttpServletResponse response,String name)
Parameter[] parameters = method.getParameters();
for (int j = 0; j < parameters.length; j++) {
Parameter parameter = parameters[j];
if(parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
// 如果是request和response物件,那麼引數名稱寫HttpServletRequest和HttpServletResponse
handler.getParamIndexMapping().put(parameter.getType().getSimpleName(),j);
}else{
handler.getParamIndexMapping().put(parameter.getName(),j); // <name,2>
}
}
// 建立url和method之間的對映關係(map快取起來)
handlerMapping.add(handler);
}
}
}
正式呼叫請求的doPost方法:
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//真正處理請求
//根據uri獲取到能處理當前請求的handler(從handlerMapping(List)中獲取)
Handler handler=getHandler(req);
if(handler==null) {
resp.getWriter().write("404 not found");
return ;
}
//引數繫結,獲取所有引數型別陣列,這個陣列長度就是我們最後要傳入的args陣列的長度
Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
//根據上述陣列長度建立一個新的陣列(引數陣列,使要傳入反射呼叫的)
Object[] paraValues = new Object[parameterTypes.length];
//以下是為了向引數陣列中塞值,而且還得保證引數的順序和方法中的形參順序一致
Map<String, String[]> parameterMap = req.getParameterMap();
//遍歷request中所有引數
for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
//name=1&name=2 name[1,2]
String value = StringUtils.join(param.getValue(), ","); //如同1,2
//如果引數和方法中的引數匹配上了,則填充資料
if(!handler.getParamIndexMapping().containsKey(param.getKey())){continue;}
Integer index = handler.getParamIndexMapping().get(param.getKey()); //name 在第二個位置
paraValues[index] = value; //把前臺傳過來的引數值填充到對應的位置去
}
Integer requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName()); //0
paraValues[requestIndex]=req;
Integer responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName()); //1
paraValues[responseIndex]=resp;
//最終呼叫handler的method屬性
try {
handler.getMethod().invoke(handler.getController(),paraValues);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
private Handler getHandler(HttpServletRequest req) {
if(handlerMapping.isEmpty()){return null;}
String url=req.getRequestURI();
for (Handler handler : handlerMapping) {
Matcher matcher = handler.getPattern().matcher(url);
if(matcher.matches()){continue;}
return handler;
}
return null;
}
pom.xml
需要定義編譯器的編譯細節,為了讓編譯器編譯的時候能夠記住形參的名字,而不是args1...等等。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lagou.edu</groupId>
<artifactId>mvc</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>mvc Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<!--編譯外掛定義編譯細節-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>11</source>
<target>11</target>
<encoding>utf-8</encoding>
<!--告訴編譯器,編譯的時候記錄下形參的真實名稱-->
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>8080</port>
<path>/</path>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
至此,我們手寫SpringMVC框架已經基本完成。
歡迎訪問:
微信公眾號(程式設計師資料站):code_data