手写Spring、SpringMVC
2020-07-01 18:46:09 763
目前实现了以下注解
@Autowired 从容器中自动注入
@Bean 标记方法返回值加入容器管理
@Component 标记此类加入容器管理
@RestController 标记此类为Rest风格的控制器 结果默认转为json
@RequestMapping 前置匹配路径
@GetMapping 匹配一个Get请求
@PutMapping 匹配一个Put请求
@DeleteMapping 匹配一个Delete请求
@PostMapping 匹配一个Post请求
@PatchMapping 匹配一个Patch请求
@ExceptionHandler 标记此方法处理一个异常
项目地址https://github.com/MQPearth/SimpleFrame
先来测试一下
用源码构建好的jar包,加入依赖,工程目录如下
config
加上@Bean注解
package com.test.config;
import simpleframe.annotation.bean.Bean;
public class ApplicationConfig {
@Bean
public String getApplicationName() {
return "Hello Simple Frame";
}
}
Result
定义响应结果类
package com.test.model;
public class Result {
public static final int RESULT_OK = 200;
private Integer code;
private String message;
private Result() {
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public static Result resultFactory(int code, String message) {
Result result = new Result();
result.setCode(code);
result.setMessage(message);
return result;
}
}
controller
写一个控制器
package com.test.controller;
import com.test.model.Result;
import simpleframe.annotation.bean.Autowired;
import simpleframe.annotation.mvc.GetMapping;
import simpleframe.annotation.mvc.RequestMapping;
import simpleframe.annotation.mvc.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/simpleframe")
public class HelloController {
@Autowired
private String applicationName;
/**
* 线程安全
*/
@Autowired
private HttpServletRequest request;
@GetMapping("/hello")
public Result hello() {
System.out.println(request.getRequestURL());
return Result.resultFactory(Result.RESULT_OK, applicationName);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>startupservlet</servlet-name>
<servlet-class>simpleframe.servlet.StartUpServlet</servlet-class>
<!-- 随容器启动 -->
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>startupservlet</servlet-name>
<!-- 匹配所有路径 -->
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
测试接口
启动容器,访问接口