简介
DynamicApi是一款针对SpringBoot项目中,简化Controller代码的工具,通过使用@DynamicApi
注解,将Service代码映射为可访问的api地址。
依赖
maven依赖
<dependency>
<groupId>io.github.zhaord</groupId>
<artifactId>dynamic-api-boot-starter</artifactId>
<version>0.3</version>
</dependency>
复制代码
gradle依赖
compile group: 'io.github.zhaord', name: 'dynamic-api-boot-starter', version: '0.3'
复制代码
Hello World
创建一个service impl,比如命名为 UserService,并创建一个方法 getHello,使用 DynamicApi
注解这个类
@DynamicApi
public class UserService {
public String getHello(String name){
return "hello,"+name;
}
}
复制代码
运行项目,通过浏览器访问 http://localhost:8080/api/service/user/getHello?name=zhaord
映射路径
比如UserService类,代码如下
@DynamicApi
public class UserService {
public String getHello(String name){
return "hello,"+name;
}
public String sayHello(String name){
return "say hello,"+name;
}
public String addName(String name){
return "add,"+name;
}
public String updateName(String name){
return "update,"+name;
}
public String removeName(String name){
return "remove,"+name;
}
}
复制代码
映射路径如下
-
[Http Get] /api/service/user/getHello
-
[Http Post] /api/service/user/sayHello
-
[Http Post] /api/service/user/saveName
-
[Http Put] /api/service/user/updateName
-
[Http Delete] /api/service/user/removeName
映射规则
-
生成的可访问接口, /api/service 为固定前缀
-
UserService类 映射为 /user,具体是类的名称首字母小写,去掉 Service、AppService、Application、ApplicationService 的后缀,
-
方法映射
-
get / find 开始的方法名映射为 http get
-
add/ insert/ post 开始的方法名映射为 http post
-
update/ put/ 开始的方法名映射为 http put
-
del/ delete/remove 开始的方法映射为 http delete
-
不符合以上规则,默认映射为 http post
-
原理
DynamicApi
注解 继承 Service
和 RestController
注解
Service
注解将Service实现类自动注册到Spring容器中RestController
注解将作用到访问,匹配RequestResponseBodyMethodProcessor
类
参数解析
普通的Controller,参数需要添加 Requestbody
或者是 RequestParam
注解,dynamic api为了不添加这些注解,定义了DynamicControllerHandlerMethodArgumentResolver
参数解析 ,这个类继承了RequestResponseBodyMethodProcessor
,添加 DynamicApi
支持
@Override
public boolean supportsParameter(MethodParameter parameter) {
if (parameter.getMethod().getName().startsWith("get")||
parameter.getMethod().getName().startsWith("find")){
return super.supportsParameter(parameter);
}
Class<?> declaringClass = parameter.getMember().getDeclaringClass();
if (declaringClass.getAnnotation(DynamicApi.class)!=null){
return true;
}
return super.supportsParameter(parameter);
}
复制代码
注册访问地址
主要是使用RequestMappingHandlerMapping
注册地址,将bean 和 方法与路径进行关联
private void processer(DynamicApiControllerInfo controllerInfo){
for (Map.Entry<String,DynamicApiMethodInfo> entry:
controllerInfo.getMethodMap().entrySet()) {
// 注册访问地址
RequestMappingInfo.Builder mappingInfoBuilder =
RequestMappingInfo.paths(DynamicApiHelper.url("api/service",
DynamicApiHelper.toCamelCase(controllerInfo.getBeanClassName()),
entry.getKey()))
.methods(DynamicApiHelper.getRequestMethod(entry.getKey()))
.options(this.config);
requestMappingHandlerMapping.registerMapping(
mappingInfoBuilder
.build(),
controllerInfo.getBeanName(),
entry.getValue().getMethod());
}
}