templates.spring.spring.web.controller.class.vm Maven / Gradle / Ivy
The newest version!
#parse( "${include}/header.include.vm" )
#parse("${include}/generic.include.vm")
#set ( $implName = "${sourceinfo.baseClass.simpleName}")
#set ( $className ="${implName}SpringWebController")
#set ( $sourceinfo.generatePackage = $pkg )
$codewriter.setCurrentJavaFilename("$pkg", "${className}.java")
## 读取源码注释
#set ($interfaceDoc = $JavadocReader.read(${sourceinfo.baseClass}))
#set( $tmp = $sourceinfo.importedList.remove("IOException"))
## 生成参数封装类名
#macro(argsClass)$TOOL.toClassName($method.name)${sourceinfo.methodSuffix($method)}Args#end
package $pkg;
#outputImports()
#if($config.useCommonResponse)
import static com.gitee.l0km.com4j.basex.web.DefaultResponseFactory.loadResponseFactory;
import com.gitee.l0km.com4j.basex.web.Response;
import com.gitee.l0km.com4j.basex.web.ResponseFactory;
import com.gitee.l0km.com4j.basex.web.TranformValueException;
#else
import java.util.ServiceLoader;
import java.util.Iterator;
import java.io.PrintWriter;
import java.io.StringWriter;
#end###if($config.useCommonResponse)
#if($config.timecost)
import com.gitee.l0km.aocache.annotations.AoTimecost;
#end###if($config.timecost)
#if($config.withDelegateMethod)
import com.gitee.l0km.codegen.annotations.DelegateMethod;
#end
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
/**
* decorator pattern 装饰者模式代理{@link #typeName(${sourceinfo.baseClass})}中有{@link RequestMapping}注释且非覆盖(Override)的方法
* 将{@link #typeName(${sourceinfo.baseClass})}实例封装为一个spring controller
* $GENERAED_BY
*/
@RestController("instanceOf${className}")
@Api(value="${implName}",tags={"${implName} Spring Controller"})
#if(!${sourceinfo.annotationOf($sourceinfo.baseClass).empty})
${sourceinfo.annoationCodeOf($sourceinfo.baseClass,"
")}
#end
public class ${className} {
private static final Logger logger = LoggerFactory.getLogger(${className}.class);
public static final ResponseFactory responseFactory = loadResponseFactory();
@Autowired
private ${implName} delegate;
@Value("${${className}.logError:true}")
private boolean logError = true ;
@Value("${${className}.trace:true}")
private boolean trace = true ;
public ${className}() {
}
/**
* @return 返回被装饰的{@link #typeName(${sourceinfo.baseClass})}实例
*/
private #typeName(${sourceinfo.baseClass}) delegate() {
return Objects.requireNonNull(delegate,"${implName} instance is null");
}
#set($methodCount = 0 )
#foreach ($method in $TOOL.sortBySignature($methods))
#set($methodCount= $methodCount + 1 )
#set ($methodDoc = $!{interfaceDoc.getMethodDoc($method.delegate())})
#set($firstLinePrefix = "")
#set($deprecated = $method.deprecated || $!{interfaceDoc.isDeprecated($methodDoc)})
#if($deprecated)
#set($firstLinePrefix = "【废弃方法】")
#end
#set($httpMethod=${sourceinfo.requestMethodOf($method,"POST")})
#set($paramPrefix = "")
// port-$methodCount
#if($deprecated)
@SuppressWarnings("deprecation")
#end
@ResponseBody
@ApiOperation(value = "${firstLinePrefix}$TOOL.firstLine($!{interfaceDoc.commentTextOf($method.delegate())},true)", notes = $TOOL.asJavaString($!{interfaceDoc.commentTextOf($method.delegate())}," \n", true),httpMethod="$httpMethod"${sourceinfo.appendProducesIfNoempty($method)})
#if($config.timecost && !${sourceinfo.withAnnotation($method,"com.gitee.l0km.aocache.annotations.AoTimecost")})
@AoTimecost
#end###if($config.timecost)
#if($config.withDelegateMethod)
@DelegateMethod(
delegateType = #typeName(${sourceinfo.baseClass}).class,
name = "$method.name"#if(${method.parameterTypes.size()}>0),
parameterTypes={#join($method.parameterTypes '#typeName($e).class' ',')},
parameterNames={#join($method.parameterNames '"$e"' ',')}#end)
#end
## 如果有方法注解(Annotation)则复制方法注解
#if(!${sourceinfo.annotationOf($method).empty})
${sourceinfo.annoationCodeOf($method,"
")}
#end
#if($httpMethod == "POST" || $httpMethod == "PUT")
#if($sourceinfo.hasInputStreamSourcePamameter($method))
#set($paramPrefix = "")
## 上传文件参数
@ApiImplicitParams({
#foreach( $param in $method.parameters )
@ApiImplicitParam(name = "$param.name", value =$TOOL.asJavaString($!{interfaceDoc.parameterCommentOf($method.delegate(),$param.name)}," \n",true) ,required =${sourceinfo.isRequired($param)} ,dataType="$TOOL.swaggerDataType(${param.type})",paramType = "form"$!{sourceinfo.defaultValueCodeOf($param,",")})#if( $velocityCount < $method.parameters.size() ),#end
#end###foreach( $param in $method.parameters )
})
public Response ${method.name}(##
#foreach( $param in $method.parameters )
#if($velocityCount>1), #end##
## 如果有参数注解(Annotation)则复制参数注解
#if(!${sourceinfo.annotationOf($param).empty})
${sourceinfo.annoationCodeOf($param,"")}##
#end##
#typeName($sourceinfo.actualTypeOf($param)) ${param.name}##
#end)
#else
#set($paramname = "args")
#set($paramPrefix = "$paramname.")
public Response ${method.name}(#if($method.parameters.size() > 0) @Validated @RequestBody #argsClass() $paramname#end)
#end###if($sourceinfo.hasInputStreamSourcePamameter($method))
#elseif($httpMethod == "GET" || $httpMethod == "DELETE")
#if($method.parameters.size() > 0)
@ApiImplicitParams({
#foreach( $param in $method.parameters )
@ApiImplicitParam(name = "$param.name", value =$TOOL.asJavaString($!{interfaceDoc.parameterCommentOf($method.delegate(),$param.name)}," \n",true) ,required =${sourceinfo.isRequired($param)} ,dataType="$TOOL.swaggerDataType(${param.type})",paramType = "query"$!{sourceinfo.defaultValueCodeOf($param,",")})#if( $velocityCount < $method.parameters.size() ),#end
#end###foreach( $param in $method.parameters )
})
#end###if($method.parameters.size() > 0)
public Response ${method.name}(#if($method.parameters.size() > 0)
#foreach( $param in $method.parameters )
@Validated @RequestParam(required =${sourceinfo.isRequired($param)}$!{sourceinfo.defaultValueCodeOf($param,",")})
## 如果有参数注解(Annotation)则复制参数注解
#if(!${sourceinfo.annotationOf($param).empty})
${sourceinfo.annoationCodeOf($param,"
")}
#end
#typeName($sourceinfo.actualTypeOf($param)) $param.name#if( $velocityCount < $method.parameters.size() ),##
#end
#end###foreach( $param in $method.parameters )
#end)
#else
/////// INVALID httpMethod=$httpMethod ///////////
#end
{
Response response = responseFactory.createResponse();
response.delegate(delegate);
try{
#if($TOOL.isVoid($method.returnType))
delegate().${method.name}(#join($method.parameters '$paramPrefix$e.name' ','));
#if(${sourceinfo.needResponse($method)})
response.onComplete();
#else
return null;
#end
#elseif($sourceinfo.isIsLocalMethod($method))
response.onComplete(false);
#else
response.onComplete(delegate().${method.name}(#join($method.parameters '$paramPrefix$e.name' ',')));
#end
}
catch(Exception e){
if(!(e instanceof TranformValueException)){
if(trace)
logger.error(e.getMessage(),e);
else if(logError){
logger.error(e.getMessage());
}
}
response.onError(e);
}
return response;
}
#end##foreach
#set($methodCount = 0 )
#foreach ($method in $TOOL.sortBySignature($methods))
#set($methodCount= $methodCount + 1 )
#set ($methodDoc = $!{interfaceDoc.getMethodDoc($method.delegate())})
#set($httpMethod=${sourceinfo.requestMethodOf($method,"POST")})
#if($httpMethod == "POST" || $httpMethod == "PUT")
#if($method.parameters.size() > 0 && !$sourceinfo.hasInputStreamSourcePamameter($method))
/**
* argClass-$methodCount
* wrap arguments for method {@link #${method.name}(#argsClass())}
*/
@ApiModel("${className}${esc.d}#argsClass()")
public static class #argsClass(){
#foreach( $param in $method.parameters )
## 如果有参数注解(Annotation)则复制参数注解
#if(!${sourceinfo.annotationOf($param).empty})
${sourceinfo.annoationCodeOf($param,"
")}
#end
@ApiModelProperty(value =$TOOL.asJavaString($!{interfaceDoc.parameterCommentOf($method.delegate(),$param.name)}," \n",true) ,required =${sourceinfo.isRequired($param)} ,dataType="$TOOL.swaggerDataType(${param.type})")
public #typeName($sourceinfo.actualTypeOf($param)) $param.name;
#end###foreach( $param in $method.parameters )
}
#end###if($method.parameters.size() > 0 && !$sourceinfo.hasInputStreamSourcePamameter($method))
#end###if($httpMethod == "POST")
#end###foreach ($method in $TOOL.sortBySignature($methods))
#if(!$config.useCommonResponse)
/**
* SPI(Service Provider Interface)加载{@link ResponseFactory}接口实例,
* 没有找到则返回{@link DefaultResponseFactory}实例
* @return 返回{@link ResponseFactory}实例
*/
private static final ResponseFactory loadResponseFactory() {
ServiceLoader providers = ServiceLoader.load(ResponseFactory.class);
Iterator itor = providers.iterator();
return itor.hasNext() ? itor.next() : new DefaultResponseFactory();
}
/**
* web响应数据接口
* @author guyadong
*
*/
public static interface Response{
/**
* 接口方法调用成功
* @param result 调用返回值
*/
void onComplete(Object result);
/**
* 接口方法调用成功,调用方法返回类型为void
*/
void onComplete();
/**
* 接口方法调用抛出异常
* @param e 异常
*/
void onError(Exception e);
}
/**
* 获取{@link Response}接口实例的工厂类接口
* @author guyadong
*
*/
public static interface ResponseFactory{
/**
* @return 返回新的{@link Response}接口实例
*/
Response createResponse();
}
/**
* {@link Response}默认实现
* @author guyadong
*
*/
public static class DefaultResponse implements Response{
private static boolean outStrackTrace = false;
private boolean success;
/** RPC调用的返回值 */
private Object result;
/** 异常信息 */
private String errorMessage;
/** 异常堆栈信息 */
private String stackTrace;
@Override
public void onComplete(Object result) {
this.success = true;
this.result = result;
}
@Override
public void onComplete() {
onComplete(null);
}
@Override
public void onError(Exception e) {
if(e instanceof TranformValueException){
onComplete((((TranformValueException)e).getResult()));
return ;
}
success = false;
errorMessage = e.getMessage();
if(errorMessage == null){
errorMessage = e.getClass().getSimpleName();
}
if(outStrackTrace){
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
stackTrace = writer.toString();
}
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getStackTrace() {
return stackTrace;
}
public void setStackTrace(String stackTrace) {
this.stackTrace = stackTrace;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("DefaultResponse [success=");
builder.append(success);
builder.append(", ");
if (result != null) {
builder.append("result=");
builder.append(result);
builder.append(", ");
}
if (errorMessage != null) {
builder.append("errorMessage=");
builder.append(errorMessage);
builder.append(", ");
}
if (stackTrace != null) {
builder.append("stackTrace=");
builder.append(stackTrace);
}
builder.append("]");
return builder.toString();
}
/**
* 开启输出堆栈信息(默认为不开启)
* 开发时为了调试需要获取详细的异常堆栈信息可以开启
*/
public static void enableStrackTrace() {
outStrackTrace = true;
}
}
/**
* {@link ResponseFactory}接口默认实现
* @author guyadong
*
*/
public static class DefaultResponseFactory implements ResponseFactory{
@Override
public Response createResponse() {
return new DefaultResponse();
}
}
/**
* 通过异常传递正常返回值
* @author guyadong
*
*/
public class TranformValueException extends RuntimeException {
private static final long serialVersionUID = 3098148044189108183L;
/**
* 传递的正常返回值
*/
private Object result;
public TranformValueException(Object result) {
super();
this.result = result;
}
/**
* 正常返回值
*/
public Object getResult() {
return result;
}
}
#end###if(!$config.useCommonResponse)
public static String DESCRIPTION = "${implName} 服务的 Spring Controller实现(only for Web)";
public String getDescription(){
return DESCRIPTION;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy