手寫一個Spring框架(不含AOP)
spring 手寫分三個階段:
1.配置階段:
web.xml配置
servlet初始化
2.初始化階段:
載入配置檔案
ioc容器初始化
掃描相關的類
類例項化,並注入ioc容器
將url路徑和相關method進行對映關聯
3執行階段
dopost作為入口
根據url找到method,通過反射去執行method;
response.getWriter(().wirte();
專案結構圖如下:
一.配置階段:
專案本身是maven專案,pom檔案只配了servlet-api和jetty
<?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.wj.Spring</groupId> <artifactId>Spring</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.4.5.v20170502</version> <configuration> <scanIntervalSeconds>10</scanIntervalSeconds> <httpConnector> <port>8080</port> </httpConnector> <webApp> <contextPath>/</contextPath> </webApp> </configuration> </plugin> </plugins> </build> </project>
然後建立DispatcherServlet 使其繼承HttpServlet,重寫dopost,doGet 以及 init 方法
@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 { } @Override public void init(ServletConfig config) throws ServletException { }
配置web.xml 如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>demoMvc</servlet-name> <servlet-class>com.wj.spring.mvcframework.servlet.DispatcherServlet</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>demoMvc</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
配置spring 核心配置檔案application的路徑
application.properties的內容只有一個掃描路徑:
接下來配置註解:springMvc常用註解:
@Controller @Service @RequestMapping @Autowired @RequestParam
這些我們都將重寫,替換成自己的註解
1)@DemoController
package com.wj.spring.mvcframework.annotation;
import java.lang.annotation.*;
/**
* Created by 小美女 on 2018/12/9.
*/
//類上使用
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DemoController {
String value() default "";
}
2)@DemoService
package com.wj.spring.mvcframework.annotation;
import java.lang.annotation.*;
/**
* Created by 小美女 on 2018/12/9.
*/
//類上使用
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DemoService {
String value() default "";
}
3) @DemoRequestMapping
package com.wj.spring.mvcframework.annotation;
import java.lang.annotation.*;
/**
* Created by 小美女 on 2018/12/9.
*/
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DemoRequestMapping {
String value() default "";
}
4)@Autowired
package com.wj.spring.mvcframework.annotation;
import java.lang.annotation.*;
/**
* Created by 小美女 on 2018/12/9.
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DemoAutowired {
String value() default "";
}
5) @DemoRequestParam 該註解因為在配置時把引數名字寫死了,所以下文沒用上
package com.wj.spring.mvcframework.annotation;
import java.lang.annotation.*;
/**
* Created by 小美女 on 2018/12/9.
*/
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DemoRequestParam {
String value() default "";
}
建立測試類:DemoAction ; DemoServiceImpl implements MyService
1)DemoAction:
package com.wj.spring.demo.action;
import com.wj.spring.demo.service.MyService;
import com.wj.spring.mvcframework.annotation.DemoAutowired;
import com.wj.spring.mvcframework.annotation.DemoController;
import com.wj.spring.mvcframework.annotation.DemoRequestMapping;
import com.wj.spring.mvcframework.annotation.DemoRequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by 小美女 on 2018/12/9.
*/
@DemoController
@DemoRequestMapping("/demo")
public class DemoAction {
@DemoAutowired
private MyService myService;
@DemoRequestMapping("/query")
public void query(HttpServletRequest req, HttpServletResponse resp,@DemoRequestParam("name") String name){
String result =myService.get(name);
try {
//寫入頁面
resp.getWriter().write(result);
}catch (Exception e){
e.printStackTrace();
}
}
@DemoRequestMapping("/add")
public void add(HttpServletRequest req,HttpServletResponse resp,@DemoRequestParam("a") Integer a,@DemoRequestParam("b") Integer b){
try {
resp.getWriter().write(a+"+"+b+"="+(a+b));
}catch (Exception e){
e.printStackTrace();
}
}
@DemoRequestMapping("/remove")
public void remove(HttpServletRequest req,HttpServletResponse resp,@DemoRequestParam("id") Integer id){
}
}
2)MyService:
package com.wj.spring.demo.service;
/**
* Created by 小美女 on 2018/12/9.
*/
public interface MyService {
public String get(String name);
}
3) DemoServiceImpl implements MyService:
package com.wj.spring.demo.service.impl;
import com.wj.spring.demo.service.MyService;
import com.wj.spring.mvcframework.annotation.DemoService;
/**
* Created by 小美女 on 2018/12/9.
*/
@DemoService
public class DemoServiceImpl implements MyService {
public String get(String name) {
return "my name is :"+name;
}
}
2.初始化階段:
在DispatcherServlet中新增成員變數;
當web專案啟動時,會啟動Servlet容器並載入DispatcherServlet 的init()方法,從init()方法的引數中,我們可以拿到application.properties檔案的路徑,並讀取其中的屬性(掃描路徑);在init()方法中新增初始化內容:
@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("my Spring init");
}
1)doLoadConfig()方法,將配置檔案讀取到Pripeties 中
private void doLoadConfig(String contextConfigLocation) {
//反射載入過程有講到過讀取classPath下的配置檔案方法
InputStream is = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
try {
contextConfig.load(is);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2)doScanner(),遞迴掃描所有的Class檔案
private void doScanner(String scanPackage) {
//得到一個url(將所有的“.“替換成”/“)
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")){ //如果不是資料夾,是檔案
String className = (scanPackage+"."+file.getName()).replace(".class","");
//獲取到所有class檔案的路徑,存入一個list中
classNames.add(className);
}
}
}
}
3)doInstance()方法,初始化相關的類,並將其放入Ioc容器中(一個map)ioc的key預設是類名首字母小寫,為此還寫了個lowerFirstCase(String beanName) 方法:
private void doInstance() {
//將掃描到的類進行反射
try {
if(classNames.isEmpty()){
return;
}
for(String className : classNames){
Class<?> clazz = Class.forName(className);
//將例項化後的物件儲存進IOC容器;
if(clazz.isAnnotationPresent(DemoController.class)){
Object o = clazz.newInstance();
//類名首字母小寫,建立一個lowerFirstCase方法(轉換成char[] 陣列操作 chars[0]+=32)
String beanName = lowerFirstCase(clazz.getSimpleName());
ioc.put(beanName,o);
}else if(clazz.isAnnotationPresent(DemoService.class)){
// service 注入的不是他本身,而是它的實現類
//1.預設類名首字母小寫(Interface)
//2.自定義beanName;
DemoService demoService = clazz.getAnnotation(DemoService.class);
String beanName = demoService.value();
if("".equals(beanName)){
beanName = lowerFirstCase(clazz.getSimpleName());
}
Object o = clazz.newInstance();
ioc.put(beanName,o);
//3. 如果是介面的實現(impl)的話,用他的介面型別作為key
Class<?>[] interfaces = clazz.getInterfaces();
for(Class<?> i :interfaces){
//如果一個介面有多個實現類,會出現重複的情況
if(ioc.containsKey(i.getName())){
throw new Exception("The beanName is exists");
}
ioc.put(i.getName(),o);
}
}else{
continue;
}
}
}catch (Exception e){
e.printStackTrace();
}
}
private String lowerFirstCase(String simpleName) {
char[] chars = simpleName.toCharArray();
chars[0]+=32;
return String.valueOf(chars);
}
4)doAutowired()方法,為Ioc容器中類的屬性賦值
private void doAutowired() {
if(ioc.isEmpty()){
return;
}
for(Map.Entry<String,Object> entry:ioc.entrySet()){
//獲取所有屬性(包括私有)
Field[] fields = entry.getValue().getClass().getDeclaredFields();
for(Field field :fields){
//只注入Autowired註解
if(!field.isAnnotationPresent(DemoAutowired.class)){continue;}
DemoAutowired demoAutowired = field.getAnnotation(DemoAutowired.class);
String beanName = demoAutowired.value().trim();
if("".equals(beanName)){//如果註解裡的屬性名是空的話,使用類名
beanName = field.getType().getName();
}
field.setAccessible(true);
try {
//使用反射為屬性賦值
field.set(entry.getValue(),ioc.get(beanName));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
5)initHandlerMapping()方法,將訪問時的url和DemoAction 的方法關聯
private void initHandlerMapping() {
//找到方法路徑
if(ioc.isEmpty()){return;}
for(Map.Entry<String,Object> entry : ioc.entrySet()){
Class<?> clazz = entry.getValue().getClass();
if(!clazz.isAnnotationPresent(DemoController.class)){
continue;
}
String baseUrl = "";
if(clazz.isAnnotationPresent(DemoRequestMapping.class)){
DemoRequestMapping demoRequestMapping = clazz.getAnnotation(DemoRequestMapping.class);
baseUrl = demoRequestMapping.value();
}
//這裡不需要獲取private的方法,Spring原始碼中也是這樣的
Method[] methods = clazz.getMethods();
for(Method method:methods){
//只用requestMapping 的方法才需要對映
if(!method.isAnnotationPresent(DemoRequestMapping.class)){
continue;
}
DemoRequestMapping demoRequestMapping = method.getAnnotation(DemoRequestMapping.class);
//多個“/” 替換成一個“/”;
String url = ("/"+baseUrl+"/"+demoRequestMapping.value()).replaceAll("/+","/");
handlerMapping.put(url,method);
System.out.println("Mapped:"+url+","+method);
}
}
}
3.執行階段
執行時,使用者傳送的請求都會被DispatcherServlet 接受,統一呼叫dopost方法,因此在dopost()方法中新增doDispatch()方法
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//執行階段,根據使用者請求的url,進行調動
try {
doDispatch(req,resp);
}catch (Exception e){
e.printStackTrace();
resp.getWriter().write("500 Detail:"+ Arrays.toString(e.getStackTrace()));
}
}
private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
if(this.handlerMapping.isEmpty()){return;}
//絕對路徑
String url = req.getRequestURI();
//絕對路徑處理成相對路徑
String contextPath = req.getContextPath();
url = url.replace(contextPath,"").replaceAll("/+","/");
if(!this.handlerMapping.containsKey(url)){
resp.getWriter().write("404 NOT FOUND");
return;
}
Method method =this.handlerMapping.get(url);
//反射呼叫
//1.方法所在類的例項(從IOC容器中拿)
//這裡沒有辦法獲得IOCmap中的key,只能通過方法所在類的類名首字母小寫獲得,與Spring的方法不同
String beanName = lowerFirstCase(method.getDeclaringClass().getSimpleName());
//瀏覽器引數
Map<String,String[]>params = new HashMap<String, String[]>();
params = req.getParameterMap();
method.invoke(ioc.get(beanName),new Object[]{req,resp,params.get("name")[0]});
}
到此整個配置完成;在瀏覽器輸入地址:
、
以下是DispatcherServlet的全部程式碼:
package com.wj.spring.mvcframework.servlet;
import com.wj.spring.mvcframework.annotation.DemoAutowired;
import com.wj.spring.mvcframework.annotation.DemoController;
import com.wj.spring.mvcframework.annotation.DemoRequestMapping;
import com.wj.spring.mvcframework.annotation.DemoService;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
/**
* Created by 小美女 on 2018/12/9.
*/
public class DispatcherServlet extends HttpServlet{
private Properties contextConfig = new Properties();
private List<String> classNames = new ArrayList<String>();
//ioc容器
Map<String,Object> ioc = new HashMap<String, Object>();
//類裡面的方法集合
Map<String,Method> handlerMapping = new HashMap<String, Method>();
@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 {
//執行階段,根據使用者請求的url,進行調動
try {
doDispatch(req,resp);
}catch (Exception e){
e.printStackTrace();
resp.getWriter().write("500 Detail:"+ Arrays.toString(e.getStackTrace()));
}
}
private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
if(this.handlerMapping.isEmpty()){return;}
//絕對路徑
String url = req.getRequestURI();
//絕對路徑處理成相對路徑
String contextPath = req.getContextPath();
url = url.replace(contextPath,"").replaceAll("/+","/");
if(!this.handlerMapping.containsKey(url)){
resp.getWriter().write("404 NOT FOUND");
return;
}
Method method =this.handlerMapping.get(url);
//反射呼叫
//1.方法所在類的例項(從IOC容器中拿)
//這裡沒有辦法獲得IOCmap中的key,只能通過方法所在類的類名首字母小寫獲得,與Spring的方法不同
String beanName = lowerFirstCase(method.getDeclaringClass().getSimpleName());
//瀏覽器引數
Map<String,String[]>params = new HashMap<String, String[]>();
params = req.getParameterMap();
method.invoke(ioc.get(beanName),new Object[]{req,resp,params.get("name")[0]});
}
@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("my Spring init");
}
private void initHandlerMapping() {
//找到方法路徑
if(ioc.isEmpty()){return;}
for(Map.Entry<String,Object> entry : ioc.entrySet()){
Class<?> clazz = entry.getValue().getClass();
if(!clazz.isAnnotationPresent(DemoController.class)){
continue;
}
String baseUrl = "";
if(clazz.isAnnotationPresent(DemoRequestMapping.class)){
DemoRequestMapping demoRequestMapping = clazz.getAnnotation(DemoRequestMapping.class);
baseUrl = demoRequestMapping.value();
}
//這裡不需要獲取private的方法,Spring原始碼中也是這樣的
Method[] methods = clazz.getMethods();
for(Method method:methods){
//只用requestMapping 的方法才需要對映
if(!method.isAnnotationPresent(DemoRequestMapping.class)){
continue;
}
DemoRequestMapping demoRequestMapping = method.getAnnotation(DemoRequestMapping.class);
//多個“/” 替換成一個“/”;
String url = ("/"+baseUrl+"/"+demoRequestMapping.value()).replaceAll("/+","/");
handlerMapping.put(url,method);
System.out.println("Mapped:"+url+","+method);
}
}
}
private void doAutowired() {
if(ioc.isEmpty()){
return;
}
for(Map.Entry<String,Object> entry:ioc.entrySet()){
//獲取所有屬性(包括私有)
Field[] fields = entry.getValue().getClass().getDeclaredFields();
for(Field field :fields){
//只注入Autowired註解
if(!field.isAnnotationPresent(DemoAutowired.class)){continue;}
DemoAutowired demoAutowired = field.getAnnotation(DemoAutowired.class);
String beanName = demoAutowired.value().trim();
if("".equals(beanName)){//如果註解裡的屬性名是空的話,使用類名
beanName = field.getType().getName();
}
field.setAccessible(true);
try {
//使用反射為屬性賦值
field.set(entry.getValue(),ioc.get(beanName));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
private void doInstance() {
//將掃描到的類進行反射
try {
if(classNames.isEmpty()){
return;
}
for(String className : classNames){
Class<?> clazz = Class.forName(className);
//將例項化後的物件儲存進IOC容器;
if(clazz.isAnnotationPresent(DemoController.class)){
Object o = clazz.newInstance();
//類名首字母小寫,建立一個lowerFirstCase方法(轉換成char[] 陣列操作 chars[0]+=32)
String beanName = lowerFirstCase(clazz.getSimpleName());
ioc.put(beanName,o);
}else if(clazz.isAnnotationPresent(DemoService.class)){
// service 注入的不是他本身,而是它的實現類
//1.預設類名首字母小寫(Interface)
//2.自定義beanName;
DemoService demoService = clazz.getAnnotation(DemoService.class);
String beanName = demoService.value();
if("".equals(beanName)){
beanName = lowerFirstCase(clazz.getSimpleName());
}
Object o = clazz.newInstance();
ioc.put(beanName,o);
//3. 如果是介面的實現(impl)的話,用他的介面型別作為key
Class<?>[] interfaces = clazz.getInterfaces();
for(Class<?> i :interfaces){
//如果一個介面有多個實現類,會出現重複的情況
if(ioc.containsKey(i.getName())){
throw new Exception("The beanName is exists");
}
ioc.put(i.getName(),o);
}
}else{
continue;
}
}
}catch (Exception e){
e.printStackTrace();
}
}
private String lowerFirstCase(String simpleName) {
char[] chars = simpleName.toCharArray();
chars[0]+=32;
return String.valueOf(chars);
}
private void doScanner(String scanPackage) {
//得到一個url(將所有的“.“替換成”/“)
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")){ //如果不是資料夾,是檔案
String className = (scanPackage+"."+file.getName()).replace(".class","");
//獲取到所有class檔案的路徑,存入一個list中
classNames.add(className);
}
}
}
}
private void doLoadConfig(String contextConfigLocation) {
//反射載入過程有講到過讀取classPath下的配置檔案方法
InputStream is = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
try {
contextConfig.load(is);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}