下面列出了org.springframework.core.MethodParameter#isOptional ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception {
NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);
MethodParameter nestedParameter = parameter.nestedIfOptional();
Object resolvedName = resolveEmbeddedValuesAndExpressions(namedValueInfo.name);
if (resolvedName == null) {
throw new IllegalArgumentException(
"Specified name must not resolve to null: [" + namedValueInfo.name + "]");
}
Object arg = resolveArgumentInternal(nestedParameter, message, resolvedName.toString());
if (arg == null) {
if (namedValueInfo.defaultValue != null) {
arg = resolveEmbeddedValuesAndExpressions(namedValueInfo.defaultValue);
}
else if (namedValueInfo.required && !nestedParameter.isOptional()) {
handleMissingValue(namedValueInfo.name, nestedParameter, message);
}
arg = handleNullValue(namedValueInfo.name, arg, nestedParameter.getNestedParameterType());
}
else if ("".equals(arg) && namedValueInfo.defaultValue != null) {
arg = resolveEmbeddedValuesAndExpressions(namedValueInfo.defaultValue);
}
if (parameter != nestedParameter || !ClassUtils.isAssignableValue(parameter.getParameterType(), arg)) {
arg = this.conversionService.convert(arg, TypeDescriptor.forObject(arg), new TypeDescriptor(parameter));
}
handleResolvedValue(arg, namedValueInfo.name, parameter, message);
return arg;
}
@Override
public Object resolveArgumentValue(MethodParameter parameter, Message<?> message) {
NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);
MethodParameter nestedParameter = parameter.nestedIfOptional();
Object resolvedName = resolveEmbeddedValuesAndExpressions(namedValueInfo.name);
if (resolvedName == null) {
throw new IllegalArgumentException(
"Specified name must not resolve to null: [" + namedValueInfo.name + "]");
}
Object arg = resolveArgumentInternal(nestedParameter, message, resolvedName.toString());
if (arg == null) {
if (namedValueInfo.defaultValue != null) {
arg = resolveEmbeddedValuesAndExpressions(namedValueInfo.defaultValue);
}
else if (namedValueInfo.required && !nestedParameter.isOptional()) {
handleMissingValue(namedValueInfo.name, nestedParameter, message);
}
arg = handleNullValue(namedValueInfo.name, arg, nestedParameter.getNestedParameterType());
}
else if ("".equals(arg) && namedValueInfo.defaultValue != null) {
arg = resolveEmbeddedValuesAndExpressions(namedValueInfo.defaultValue);
}
if (parameter != nestedParameter || !ClassUtils.isAssignableValue(parameter.getParameterType(), arg)) {
arg = this.conversionService.convert(arg, TypeDescriptor.forObject(arg), new TypeDescriptor(parameter));
}
return arg;
}
/**
* Build params parameter.
*
* @param parameterInfo the parameter info
* @param components the components
* @param requestMethod the request method
* @param jsonView the json view
* @return the parameter
*/
public Parameter buildParams(ParameterInfo parameterInfo, Components components,
RequestMethod requestMethod, JsonView jsonView) {
MethodParameter methodParameter = parameterInfo.getMethodParameter();
RequestHeader requestHeader = parameterInfo.getRequestHeader();
RequestParam requestParam = parameterInfo.getRequestParam();
PathVariable pathVar = parameterInfo.getPathVar();
CookieValue cookieValue = parameterInfo.getCookieValue();
RequestInfo requestInfo;
if (requestHeader != null) {
requestInfo = new RequestInfo(ParameterIn.HEADER.toString(), parameterInfo.getpName(), requestHeader.required(),
requestHeader.defaultValue());
return buildParam(parameterInfo, components, requestInfo, jsonView);
}
else if (requestParam != null && !parameterBuilder.isFile(parameterInfo.getMethodParameter())) {
requestInfo = new RequestInfo(ParameterIn.QUERY.toString(), parameterInfo.getpName(), requestParam.required() && !methodParameter.isOptional(),
requestParam.defaultValue());
return buildParam(parameterInfo, components, requestInfo, jsonView);
}
else if (pathVar != null) {
requestInfo = new RequestInfo(ParameterIn.PATH.toString(), parameterInfo.getpName(), !methodParameter.isOptional(), null);
return buildParam(parameterInfo, components, requestInfo, jsonView);
}
else if (cookieValue != null) {
requestInfo = new RequestInfo(ParameterIn.COOKIE.toString(), parameterInfo.getpName(), cookieValue.required(),
cookieValue.defaultValue());
return buildParam(parameterInfo, components, requestInfo, jsonView);
}
// By default
DelegatingMethodParameter delegatingMethodParameter = (DelegatingMethodParameter) methodParameter;
if (RequestMethod.GET.equals(requestMethod)
|| (parameterInfo.getParameterModel() != null && (ParameterIn.PATH.toString().equals(parameterInfo.getParameterModel().getIn())))
|| delegatingMethodParameter.isParameterObject())
return this.buildParam(QUERY_PARAM, components, parameterInfo, !methodParameter.isOptional(), null, jsonView);
return null;
}
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception {
NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);
MethodParameter nestedParameter = parameter.nestedIfOptional();
Object resolvedName = resolveStringValue(namedValueInfo.name);
if (resolvedName == null) {
throw new IllegalArgumentException(
"Specified name must not resolve to null: [" + namedValueInfo.name + "]");
}
Object arg = resolveArgumentInternal(nestedParameter, message, resolvedName.toString());
if (arg == null) {
if (namedValueInfo.defaultValue != null) {
arg = resolveStringValue(namedValueInfo.defaultValue);
}
else if (namedValueInfo.required && !nestedParameter.isOptional()) {
handleMissingValue(namedValueInfo.name, nestedParameter, message);
}
arg = handleNullValue(namedValueInfo.name, arg, nestedParameter.getNestedParameterType());
}
else if ("".equals(arg) && namedValueInfo.defaultValue != null) {
arg = resolveStringValue(namedValueInfo.defaultValue);
}
if (parameter != nestedParameter || !ClassUtils.isAssignableValue(parameter.getParameterType(), arg)) {
arg = this.conversionService.convert(arg, TypeDescriptor.forObject(arg), new TypeDescriptor(parameter));
}
handleResolvedValue(arg, namedValueInfo.name, parameter, message);
return arg;
}
@Override
protected boolean isRequired(MethodParameter param, RequestHeader annot) {
// Spring disallows null for primitive types
// For types wrapped in Optional or nullable Kotlin types, the required flag in
// the annotation is ignored by Spring.
return param.getParameterType().isPrimitive() || (!param.isOptional() && annot.required());
}
@Override
protected boolean isRequired(MethodParameter param, RequestParam annot) {
if (hasDefaultValue(annot)) {
// Having a defaultValue set implies required=false
return false;
} else if (param.getParameterType().isPrimitive()) {
// A primitive type is required if no defaultValue is set, regardless of the value of
// the required flag
return true;
} else {
// For Types wrapped in Optional or nullable Kotlin types, the required flag in
// the annotation is ignored by Spring.
return !param.isOptional() && annot.required();
}
}
@Override
protected boolean isRequired(MethodParameter param, PathVariable annot) {
// Spring disallows null for primitive types.
// For types wrapped in Optional or nullable Kotlin types, the required flag in
// the annotation is ignored by Spring.
return param.getParameterType().isPrimitive() || (!param.isOptional() && annot.required());
}
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
NativeWebRequest request, @Nullable WebDataBinderFactory binderFactory) throws Exception {
HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
Assert.state(servletRequest != null, "No HttpServletRequest");
RequestPart requestPart = parameter.getParameterAnnotation(RequestPart.class);
boolean isRequired = ((requestPart == null || requestPart.required()) && !parameter.isOptional());
String name = getPartName(parameter, requestPart);
parameter = parameter.nestedIfOptional();
Object arg = null;
Object mpArg = MultipartResolutionDelegate.resolveMultipartArgument(name, parameter, servletRequest);
if (mpArg != MultipartResolutionDelegate.UNRESOLVABLE) {
arg = mpArg;
}
else {
try {
HttpInputMessage inputMessage = new RequestPartServletServerHttpRequest(servletRequest, name);
arg = readWithMessageConverters(inputMessage, parameter, parameter.getNestedGenericParameterType());
if (binderFactory != null) {
WebDataBinder binder = binderFactory.createBinder(request, arg, name);
if (arg != null) {
validateIfApplicable(binder, parameter);
if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
}
}
if (mavContainer != null) {
mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
}
}
}
catch (MissingServletRequestPartException | MultipartException ex) {
if (isRequired) {
throw ex;
}
}
}
if (arg == null && isRequired) {
if (!MultipartResolutionDelegate.isMultipartRequest(servletRequest)) {
throw new MultipartException("Current request is not a multipart request");
}
else {
throw new MissingServletRequestPartException(name);
}
}
return adaptArgumentIfNecessary(arg, parameter);
}
protected boolean checkRequired(MethodParameter parameter) {
RequestBody requestBody = parameter.getParameterAnnotation(RequestBody.class);
return (requestBody != null && requestBody.required() && !parameter.isOptional());
}
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
NativeWebRequest request, @Nullable WebDataBinderFactory binderFactory) throws Exception {
HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
Assert.state(servletRequest != null, "No HttpServletRequest");
RequestPart requestPart = parameter.getParameterAnnotation(RequestPart.class);
boolean isRequired = ((requestPart == null || requestPart.required()) && !parameter.isOptional());
String name = getPartName(parameter, requestPart);
parameter = parameter.nestedIfOptional();
Object arg = null;
Object mpArg = MultipartResolutionDelegate.resolveMultipartArgument(name, parameter, servletRequest);
if (mpArg != MultipartResolutionDelegate.UNRESOLVABLE) {
arg = mpArg;
}
else {
try {
HttpInputMessage inputMessage = new RequestPartServletServerHttpRequest(servletRequest, name);
arg = readWithMessageConverters(inputMessage, parameter, parameter.getNestedGenericParameterType());
if (binderFactory != null) {
WebDataBinder binder = binderFactory.createBinder(request, arg, name);
if (arg != null) {
validateIfApplicable(binder, parameter);
if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
}
}
if (mavContainer != null) {
mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
}
}
}
catch (MissingServletRequestPartException | MultipartException ex) {
if (isRequired) {
throw ex;
}
}
}
if (arg == null && isRequired) {
if (!MultipartResolutionDelegate.isMultipartRequest(servletRequest)) {
throw new MultipartException("Current request is not a multipart request");
}
else {
throw new MissingServletRequestPartException(name);
}
}
return adaptArgumentIfNecessary(arg, parameter);
}
protected boolean checkRequired(MethodParameter parameter) {
RequestBody requestBody = parameter.getParameterAnnotation(RequestBody.class);
return (requestBody != null && requestBody.required() && !parameter.isOptional());
}
/**
* 根据path找到并发现REST Controller
*/
public static NodeMessage controllerInvoke(RequestMappingHandlerMapping requestMappingHandlerMapping, NodeMessage reqMessage) {
String path = ConversionUtil.toString(reqMessage.getField(NodeMessage.FIELD_PATH));
//匹配合适的
Object result = null;
Throwable t = null;
RequestMappingInfo reqMappingInfo=null;
HandlerMethod reqHandlerMethod = null;
Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
for(RequestMappingInfo info:map.keySet()) {
List<String> matches = info.getPatternsCondition().getMatchingPatterns(path);
if ( matches.isEmpty() ) {
continue;
}
reqMappingInfo = info;
reqHandlerMethod = map.get(info);
break;
}
if ( reqMappingInfo==null ) {
t = new Exception("Controller for "+path+" is not found");
logger.error("Controller for "+path+" is not found");
} else {
MethodParameter[] methodParams = reqHandlerMethod.getMethodParameters();
Object[] params = new Object[methodParams.length];
try{
for(int i=0;i<methodParams.length;i++) {
MethodParameter param = methodParams[i];
String paramName = param.getParameterName();
params[i] = ConversionUtil.toType(param.getParameter().getType(), reqMessage.getField(paramName));
if ( params[i]==null && !param.isOptional() ) {
throw new IllegalArgumentException("Method parameter "+paramName+" is missing");
}
}
result = reqHandlerMethod.getMethod().invoke(reqHandlerMethod.getBean(), params);
}catch(Throwable ex ) {
if ( ex instanceof InvocationTargetException ) {
t = ((InvocationTargetException)ex).getTargetException();
}else {
t = ex;
}
logger.error("Invoke controller "+path+" with params "+Arrays.asList(params)+" failed: "+t, t);
}
}
NodeMessage respMessage = reqMessage.createResponse();
if ( t!=null ) {
respMessage.setErrCode(-1);
respMessage.setErrMsg(t.toString());
} else {
respMessage.setField(NodeMessage.FIELD_RESULT, JsonUtil.object2json(result));
}
return respMessage;
}
protected boolean checkRequired(MethodParameter parameter) {
return (parameter.getParameterAnnotation(RequestBody.class).required() && !parameter.isOptional());
}
/**
* Adapt the given argument against the method parameter, if necessary.
* @param arg the resolved argument
* @param parameter the method parameter descriptor
* @return the adapted argument, or the original resolved argument as-is
* @since 4.3.5
*/
protected Object adaptArgumentIfNecessary(Object arg, MethodParameter parameter) {
return (parameter.isOptional() ? OptionalResolver.resolveValue(arg) : arg);
}