Java 类org.springframework.core.annotation.SynthesizingMethodParameter 实例源码

项目:FastBootWeixin    文件:WxApiMethodInfo.java   
private UriComponents applyContributors(UriComponentsBuilder builder, Method method, Object... args) {
    CompositeUriComponentsContributor contributor = defaultUriComponentsContributor;
    int paramCount = method.getParameterTypes().length;
    int argCount = args.length;
    if (paramCount != argCount) {
        throw new IllegalArgumentException("方法参数量为" + paramCount + " 与真实参数量不匹配,真实参数量为" + argCount);
    }
    final Map<String, Object> uriVars = new HashMap<>(8);
    for (int i = 0; i < paramCount; i++) {
        MethodParameter param = new SynthesizingMethodParameter(method, i);
        param.initParameterNameDiscovery(parameterNameDiscoverer);
        contributor.contributeMethodArgument(param, args[i], builder, uriVars);
    }
    // We may not have all URI var values, expand only what we have
    return builder.build().expand(name -> uriVars.containsKey(name) ? uriVars.get(name) : UriComponents.UriTemplateVariables.SKIP_VALUE);
}
项目:spring4-understanding    文件:HeaderMethodArgumentResolverTests.java   
@Before
public void setup() throws Exception {
    @SuppressWarnings("resource")
    GenericApplicationContext cxt = new GenericApplicationContext();
    cxt.refresh();
    this.resolver = new HeaderMethodArgumentResolver(new DefaultConversionService(), cxt.getBeanFactory());

    Method method = getClass().getDeclaredMethod("handleMessage",
            String.class, String.class, String.class, String.class, String.class);
    this.paramRequired = new SynthesizingMethodParameter(method, 0);
    this.paramNamedDefaultValueStringHeader = new SynthesizingMethodParameter(method, 1);
    this.paramSystemProperty = new SynthesizingMethodParameter(method, 2);
    this.paramNotAnnotated = new SynthesizingMethodParameter(method, 3);
    this.paramNativeHeader = new SynthesizingMethodParameter(method, 4);

    this.paramRequired.initParameterNameDiscovery(new DefaultParameterNameDiscoverer());
    GenericTypeResolver.resolveParameterType(this.paramRequired, HeaderMethodArgumentResolver.class);
}
项目:spring4-understanding    文件:AnnotationMethodHandlerExceptionResolver.java   
/**
 * Resolves the arguments for the given method. Delegates to {@link #resolveCommonArgument}.
 */
private Object[] resolveHandlerArguments(Method handlerMethod, Object handler,
        NativeWebRequest webRequest, Exception thrownException) throws Exception {

    Class<?>[] paramTypes = handlerMethod.getParameterTypes();
    Object[] args = new Object[paramTypes.length];
    Class<?> handlerType = handler.getClass();
    for (int i = 0; i < args.length; i++) {
        MethodParameter methodParam = new SynthesizingMethodParameter(handlerMethod, i);
        GenericTypeResolver.resolveParameterType(methodParam, handlerType);
        Class<?> paramType = methodParam.getParameterType();
        Object argValue = resolveCommonArgument(methodParam, webRequest, thrownException);
        if (argValue != WebArgumentResolver.UNRESOLVED) {
            args[i] = argValue;
        }
        else {
            throw new IllegalStateException("Unsupported argument [" + paramType.getName() +
                    "] for @ExceptionHandler method: " + handlerMethod);
        }
    }
    return args;
}
项目:spring4-understanding    文件:AnnotationMethodHandlerExceptionResolver.java   
/**
 * Resolves the arguments for the given method. Delegates to {@link #resolveCommonArgument}.
 */
private Object[] resolveHandlerArguments(Method handlerMethod, Object handler,
        NativeWebRequest webRequest, Exception thrownException) throws Exception {

    Class<?>[] paramTypes = handlerMethod.getParameterTypes();
    Object[] args = new Object[paramTypes.length];
    Class<?> handlerType = handler.getClass();
    for (int i = 0; i < args.length; i++) {
        MethodParameter methodParam = new SynthesizingMethodParameter(handlerMethod, i);
        GenericTypeResolver.resolveParameterType(methodParam, handlerType);
        Class<?> paramType = methodParam.getParameterType();
        Object argValue = resolveCommonArgument(methodParam, webRequest, thrownException);
        if (argValue != WebArgumentResolver.UNRESOLVED) {
            args[i] = argValue;
        }
        else {
            throw new IllegalStateException("Unsupported argument [" + paramType.getName() +
                    "] for @ExceptionHandler method: " + handlerMethod);
        }
    }
    return args;
}
项目:spring4-understanding    文件:MatrixVariablesMapMethodArgumentResolverTests.java   
@Before
public void setUp() throws Exception {
    this.resolver = new MatrixVariableMapMethodArgumentResolver();

    Method method = getClass().getMethod("handle", String.class,
            Map.class, MultiValueMap.class, MultiValueMap.class, Map.class);

    this.paramString = new SynthesizingMethodParameter(method, 0);
    this.paramMap = new SynthesizingMethodParameter(method, 1);
    this.paramMultivalueMap = new SynthesizingMethodParameter(method, 2);
    this.paramMapForPathVar = new SynthesizingMethodParameter(method, 3);
    this.paramMapWithName = new SynthesizingMethodParameter(method, 4);

    this.mavContainer = new ModelAndViewContainer();
    this.request = new MockHttpServletRequest();
    this.webRequest = new ServletWebRequest(request, new MockHttpServletResponse());

    Map<String, MultiValueMap<String, String>> params = new LinkedHashMap<String, MultiValueMap<String, String>>();
    this.request.setAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, params);
}
项目:spring4-understanding    文件:RequestHeaderMethodArgumentResolverTests.java   
@Before
@SuppressWarnings("resource")
public void setUp() throws Exception {
    GenericWebApplicationContext context = new GenericWebApplicationContext();
    context.refresh();
    resolver = new RequestHeaderMethodArgumentResolver(context.getBeanFactory());

    Method method = getClass().getMethod("params", String.class, String[].class, String.class, String.class, Map.class);
    paramNamedDefaultValueStringHeader = new SynthesizingMethodParameter(method, 0);
    paramNamedValueStringArray = new SynthesizingMethodParameter(method, 1);
    paramSystemProperty = new SynthesizingMethodParameter(method, 2);
    paramContextPath = new SynthesizingMethodParameter(method, 3);
    paramNamedValueMap = new SynthesizingMethodParameter(method, 4);

    servletRequest = new MockHttpServletRequest();
    webRequest = new ServletWebRequest(servletRequest, new MockHttpServletResponse());

    // Expose request to the current thread (for SpEL expressions)
    RequestContextHolder.setRequestAttributes(webRequest);
}
项目:autotest    文件:AutoTestExtension.java   
static Object resolveDependency(Parameter parameter, Class<?> containingClass, ApplicationContext applicationContext) {
    boolean required = findMergedAnnotation(parameter, Autowired.class).map(Autowired::required).orElse(true);
    MethodParameter methodParameter = SynthesizingMethodParameter.forParameter(parameter);
    DependencyDescriptor descriptor = new DependencyDescriptor(methodParameter, required);
    descriptor.setContainingClass(containingClass);
    return applicationContext.getAutowireCapableBeanFactory().resolveDependency(descriptor, null);
}
项目:spring4-understanding    文件:SendToMethodReturnValueHandlerTests.java   
@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);

    SimpMessagingTemplate messagingTemplate = new SimpMessagingTemplate(this.messageChannel);
    messagingTemplate.setMessageConverter(new StringMessageConverter());
    this.handler = new SendToMethodReturnValueHandler(messagingTemplate, true);
    this.handlerAnnotationNotRequired = new SendToMethodReturnValueHandler(messagingTemplate, false);

    SimpMessagingTemplate jsonMessagingTemplate = new SimpMessagingTemplate(this.messageChannel);
    jsonMessagingTemplate.setMessageConverter(new MappingJackson2MessageConverter());
    this.jsonHandler = new SendToMethodReturnValueHandler(jsonMessagingTemplate, true);

    Method method = this.getClass().getDeclaredMethod("handleNoAnnotations");
    this.noAnnotationsReturnType = new SynthesizingMethodParameter(method, -1);

    method = this.getClass().getDeclaredMethod("handleAndSendToDefaultDestination");
    this.sendToDefaultDestReturnType = new SynthesizingMethodParameter(method, -1);

    method = this.getClass().getDeclaredMethod("handleAndSendTo");
    this.sendToReturnType = new SynthesizingMethodParameter(method, -1);

    method = this.getClass().getDeclaredMethod("handleAndSendToWithPlaceholders");
    this.sendToWithPlaceholdersReturnType = new SynthesizingMethodParameter(method, -1);

    method = this.getClass().getDeclaredMethod("handleAndSendToUser");
    this.sendToUserReturnType = new SynthesizingMethodParameter(method, -1);

    method = this.getClass().getDeclaredMethod("handleAndSendToUserSingleSession");
    this.sendToUserSingleSessionReturnType = new SynthesizingMethodParameter(method, -1);

    method = this.getClass().getDeclaredMethod("handleAndSendToUserDefaultDestination");
    this.sendToUserDefaultDestReturnType = new SynthesizingMethodParameter(method, -1);

    method = this.getClass().getDeclaredMethod("handleAndSendToUserDefaultDestinationSingleSession");
    this.sendToUserSingleSessionDefaultDestReturnType = new SynthesizingMethodParameter(method, -1);

    method = this.getClass().getDeclaredMethod("handleAndSendToJsonView");
    this.jsonViewReturnType = new SynthesizingMethodParameter(method, -1);
}
项目:spring4-understanding    文件:PayloadArgumentResolverTests.java   
@Before
public void setup() throws Exception {
    this.resolver = new PayloadArgumentResolver(new StringMessageConverter(), testValidator());
    this.payloadMethod = PayloadArgumentResolverTests.class.getDeclaredMethod("handleMessage",
            String.class, String.class, Locale.class, String.class, String.class, String.class, String.class);

    this.paramAnnotated = new SynthesizingMethodParameter(this.payloadMethod, 0);
    this.paramAnnotatedNotRequired = new SynthesizingMethodParameter(this.payloadMethod, 1);
    this.paramAnnotatedRequired = new SynthesizingMethodParameter(payloadMethod, 2);
    this.paramWithSpelExpression = new SynthesizingMethodParameter(payloadMethod, 3);
    this.paramValidated = new SynthesizingMethodParameter(this.payloadMethod, 4);
    this.paramValidated.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer());
    this.paramValidatedNotAnnotated = new SynthesizingMethodParameter(this.payloadMethod, 5);
    this.paramNotAnnotated = new SynthesizingMethodParameter(this.payloadMethod, 6);
}
项目:spring4-understanding    文件:MvcUriComponentsBuilder.java   
private static UriComponents applyContributors(UriComponentsBuilder builder, Method method, Object... args) {
    CompositeUriComponentsContributor contributor = getConfiguredUriComponentsContributor();
    if (contributor == null) {
        logger.debug("Using default CompositeUriComponentsContributor");
        contributor = defaultUriComponentsContributor;
    }

    int paramCount = method.getParameterTypes().length;
    int argCount = args.length;
    if (paramCount != argCount) {
        throw new IllegalArgumentException("Number of method parameters " + paramCount +
                " does not match number of argument values " + argCount);
    }

    final Map<String, Object> uriVars = new HashMap<String, Object>();
    for (int i = 0; i < paramCount; i++) {
        MethodParameter param = new SynthesizingMethodParameter(method, i);
        param.initParameterNameDiscovery(parameterNameDiscoverer);
        contributor.contributeMethodArgument(param, args[i], builder, uriVars);
    }

    // We may not have all URI var values, expand only what we have
    return builder.build().expand(new UriComponents.UriTemplateVariables() {
        @Override
        public Object getValue(String name) {
            return uriVars.containsKey(name) ? uriVars.get(name) : UriComponents.UriTemplateVariables.SKIP_VALUE;
        }
    });
}
项目:spring4-understanding    文件:ServletCookieValueMethodArgumentResolverTests.java   
@Before
public void setUp() throws Exception {
    resolver = new ServletCookieValueMethodArgumentResolver(null);

    Method method = getClass().getMethod("params", Cookie.class, String.class);
    cookieParameter = new SynthesizingMethodParameter(method, 0);
    cookieStringParameter = new SynthesizingMethodParameter(method, 1);

    request = new MockHttpServletRequest();
    webRequest = new ServletWebRequest(request, new MockHttpServletResponse());
}
项目:spring4-understanding    文件:RequestParamMapMethodArgumentResolverTests.java   
@Before
public void setUp() throws Exception {
    resolver = new RequestParamMapMethodArgumentResolver();

    Method method = getClass().getMethod("params", Map.class, MultiValueMap.class, Map.class, Map.class);
    paramMap = new SynthesizingMethodParameter(method, 0);
    paramMultiValueMap = new SynthesizingMethodParameter(method, 1);
    paramNamedMap = new SynthesizingMethodParameter(method, 2);
    paramMapWithoutAnnot = new SynthesizingMethodParameter(method, 3);

    request = new MockHttpServletRequest();
    webRequest = new ServletWebRequest(request, new MockHttpServletResponse());
}
项目:spring4-understanding    文件:RequestParamMethodArgumentResolverTests.java   
@Before
public void setUp() throws Exception {
    resolver = new RequestParamMethodArgumentResolver(null, true);

    ParameterNameDiscoverer paramNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();

    Method method = getClass().getMethod("params", String.class, String[].class,
            Map.class, MultipartFile.class, List.class, MultipartFile[].class,
            Part.class, List.class, Part[].class, Map.class,
            String.class, MultipartFile.class, List.class, Part.class,
            MultipartFile.class, String.class, String.class, Optional.class);

    paramNamedDefaultValueString = new SynthesizingMethodParameter(method, 0);
    paramNamedStringArray = new SynthesizingMethodParameter(method, 1);
    paramNamedMap = new SynthesizingMethodParameter(method, 2);
    paramMultipartFile = new SynthesizingMethodParameter(method, 3);
    paramMultipartFileList = new SynthesizingMethodParameter(method, 4);
    paramMultipartFileArray = new SynthesizingMethodParameter(method, 5);
    paramPart = new SynthesizingMethodParameter(method, 6);
    paramPartList  = new SynthesizingMethodParameter(method, 7);
    paramPartArray  = new SynthesizingMethodParameter(method, 8);
    paramMap = new SynthesizingMethodParameter(method, 9);
    paramStringNotAnnot = new SynthesizingMethodParameter(method, 10);
    paramStringNotAnnot.initParameterNameDiscovery(paramNameDiscoverer);
    paramMultipartFileNotAnnot = new SynthesizingMethodParameter(method, 11);
    paramMultipartFileNotAnnot.initParameterNameDiscovery(paramNameDiscoverer);
    paramMultipartFileListNotAnnot = new SynthesizingMethodParameter(method, 12);
    paramMultipartFileListNotAnnot.initParameterNameDiscovery(paramNameDiscoverer);
    paramPartNotAnnot = new SynthesizingMethodParameter(method, 13);
    paramPartNotAnnot.initParameterNameDiscovery(paramNameDiscoverer);
    paramRequestPartAnnot = new SynthesizingMethodParameter(method, 14);
    paramRequired = new SynthesizingMethodParameter(method, 15);
    paramNotRequired = new SynthesizingMethodParameter(method, 16);
    paramOptional = new SynthesizingMethodParameter(method, 17);

    request = new MockHttpServletRequest();
    webRequest = new ServletWebRequest(request, new MockHttpServletResponse());
}
项目:spring4-understanding    文件:CookieValueMethodArgumentResolverTests.java   
@Before
public void setUp() throws Exception {
    resolver = new TestCookieValueMethodArgumentResolver();

    Method method = getClass().getMethod("params", Cookie.class, String.class, String.class);
    paramNamedCookie = new SynthesizingMethodParameter(method, 0);
    paramNamedDefaultValueString = new SynthesizingMethodParameter(method, 1);
    paramString = new SynthesizingMethodParameter(method, 2);

    request = new MockHttpServletRequest();
    webRequest = new ServletWebRequest(request, new MockHttpServletResponse());
}
项目:spring4-understanding    文件:RequestHeaderMapMethodArgumentResolverTests.java   
@Before
public void setUp() throws Exception {
    resolver = new RequestHeaderMapMethodArgumentResolver();

    Method method = getClass().getMethod("params", Map.class, MultiValueMap.class, HttpHeaders.class, Map.class);
    paramMap = new SynthesizingMethodParameter(method, 0);
    paramMultiValueMap = new SynthesizingMethodParameter(method, 1);
    paramHttpHeaders = new SynthesizingMethodParameter(method, 2);
    paramUnsupported = new SynthesizingMethodParameter(method, 3);

    request = new MockHttpServletRequest();
    webRequest = new ServletWebRequest(request, new MockHttpServletResponse());
}
项目:springlets    文件:SpringletsMvcUriComponentsBuilder.java   
private static UriComponents applyContributors(UriComponentsBuilder builder, Method method, Object... args) {
    CompositeUriComponentsContributor contributor = getConfiguredUriComponentsContributor();
    if (contributor == null) {
        logger.debug("Using default CompositeUriComponentsContributor");
        contributor = defaultUriComponentsContributor;
    }

    int paramCount = method.getParameterTypes().length;
    int argCount = args.length;
    if (paramCount != argCount) {
        throw new IllegalArgumentException("Number of method parameters " + paramCount +
                " does not match number of argument values " + argCount);
    }

    final Map<String, Object> uriVars = new HashMap<String, Object>();
    for (int i = 0; i < paramCount; i++) {
        MethodParameter param = new SynthesizingMethodParameter(method, i);
        param.initParameterNameDiscovery(parameterNameDiscoverer);
        contributor.contributeMethodArgument(param, args[i], builder, uriVars);
    }

    // Custom implementation to remove uriVar if the value is null
    removeUriVarsWithNullValue(uriVars);

    // We may not have all URI var values, expand only what we have
    return builder.build().expand(new UriComponents.UriTemplateVariables() {
        @Override
        public Object getValue(String name) {
            return uriVars.containsKey(name) ? uriVars.get(name) : UriComponents.UriTemplateVariables.SKIP_VALUE;
        }
    });
}
项目:spring-test-junit5    文件:MethodParameterFactory.java   
/**
 * Create a {@link SynthesizingMethodParameter} from the supplied {@link Parameter}.
 * <p>Supports parameters declared in methods.
 * @param parameter the parameter to create a {@code SynthesizingMethodParameter}
 * for; never {@code null}
 * @return a new {@code SynthesizingMethodParameter}
 * @throws UnsupportedOperationException if the supplied parameter is declared
 * in a constructor
 * @see #createMethodParameter(Parameter)
 */
public static SynthesizingMethodParameter createSynthesizingMethodParameter(Parameter parameter) {
    Assert.notNull(parameter, "Parameter must not be null");
    Executable executable = parameter.getDeclaringExecutable();
    if (executable instanceof Method) {
        return new SynthesizingMethodParameter((Method) executable, getIndex(parameter));
    }
    // else
    throw new UnsupportedOperationException(
        "Cannot create a SynthesizingMethodParameter for a constructor parameter: " + parameter);
}
项目:FastBootWeixin    文件:WxApiMethodInfo.java   
/**
 * 尝试获取请求方法,逻辑看里面
 * 有以下几种情况:1、简单类型参数与总参数相同,获取注解上的请求方式
 * 1、简单类型参数比总参数少1,即有一个请求body,则可能有两种方式,一种是表单,一种是整个请求体,如何去区分?
 * 2、少多个,则以表单提交
 *
 * @param method
 * @return dummy
 */
private WxApiRequest.Method prepareRequestInfo(Method method) {
    // 保存参数类型,如果有设置的注解类型则为注解类型
    methodParameters = IntStream.range(0, method.getParameterCount()).mapToObj(i -> {
        MethodParameter methodParameter = new SynthesizingMethodParameter(method, i);
        methodParameter.initParameterNameDiscovery(parameterNameDiscoverer);
        // 预热缓存
        methodParameter.getParameterName();
        return methodParameter;
    }).collect(Collectors.toList());
    // 是不是全是简单属性,简单属性的数量
    long simpleParameterCount = methodParameters.stream()
            .filter(p -> BeanUtils.isSimpleValueType(p.getParameterType()))
            .filter(p -> !p.hasParameterAnnotation(WxApiBody.class))
            .filter(p -> !p.hasParameterAnnotation(WxApiForm.class))
            .count();
    WxApiRequest wxApiRequest = AnnotatedElementUtils.findMergedAnnotation(method, WxApiRequest.class);
    // 简单参数数量相同
    if (simpleParameterCount == method.getParameterCount()) {
        if (wxApiRequest == null) {
            return WxApiRequest.Method.GET;
        } else {
            return wxApiRequest.method();
        }
    }
    // 非简单参数多于一个,只能是FORM表单形式
    if (method.getParameterCount() - simpleParameterCount > 1) {
        // 默认出现了wxApiForm
        isWxApiFormPresent = true;
        return WxApiRequest.Method.FORM;
    }
    // 如果有一个是文件则以FORM形式提交
    isMutlipartRequest = Arrays.stream(method.getParameters())
            .filter(p -> WxWebUtils.isMutlipart(p.getType())).findFirst().isPresent();
    if (isMutlipartRequest) {
        isWxApiFormPresent = true;
        return WxApiRequest.Method.FORM;
    }
    // 如果有ApiForm注解,则直接以FORM方式提交
    isWxApiFormPresent = methodParameters.stream()
            .filter(p -> p.hasParameterAnnotation(WxApiForm.class)).findFirst().isPresent();
    if (isWxApiFormPresent) {
        return WxApiRequest.Method.FORM;
    }
    WxApiBody wxApiBody = methodParameters.stream()
            .filter(p -> p.hasParameterAnnotation(WxApiBody.class))
            .map(p -> p.getParameterAnnotation(WxApiBody.class))
            .findFirst().orElse(null);
    if (wxApiBody == null) {
        return WxApiRequest.Method.JSON;
    }
    isWxApiBodyPresent = true;
    return WxApiRequest.Method.valueOf(wxApiBody.type().name());
}
项目:spring4-understanding    文件:RequestPartMethodArgumentResolverTests.java   
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
    Method method = getClass().getMethod("handle", SimpleBean.class, SimpleBean.class,
            SimpleBean.class, MultipartFile.class, List.class, MultipartFile[].class,
            Integer.TYPE, MultipartFile.class, Part.class, List.class, Part[].class,
            MultipartFile.class, Optional.class, Optional.class, Optional.class);

    paramRequestPart = new SynthesizingMethodParameter(method, 0);
    paramRequestPart.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer());
    paramNamedRequestPart = new SynthesizingMethodParameter(method, 1);
    paramValidRequestPart = new SynthesizingMethodParameter(method, 2);
    paramMultipartFile = new SynthesizingMethodParameter(method, 3);
    paramMultipartFileList = new SynthesizingMethodParameter(method, 4);
    paramMultipartFileArray = new SynthesizingMethodParameter(method, 5);
    paramInt = new SynthesizingMethodParameter(method, 6);
    paramMultipartFileNotAnnot = new SynthesizingMethodParameter(method, 7);
    paramMultipartFileNotAnnot.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer());
    paramPart = new SynthesizingMethodParameter(method, 8);
    paramPart.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer());
    paramPartList = new SynthesizingMethodParameter(method, 9);
    paramPartArray = new SynthesizingMethodParameter(method, 10);
    paramRequestParamAnnot = new SynthesizingMethodParameter(method, 11);
    optionalMultipartFile = new SynthesizingMethodParameter(method, 12);
    optionalMultipartFile.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer());
    optionalPart = new SynthesizingMethodParameter(method, 13);
    optionalPart.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer());
    optionalRequestPart = new SynthesizingMethodParameter(method, 14);

    messageConverter = mock(HttpMessageConverter.class);
    given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));

    resolver = new RequestPartMethodArgumentResolver(Collections.<HttpMessageConverter<?>>singletonList(messageConverter));
    reset(messageConverter);

    byte[] content = "doesn't matter as long as not empty".getBytes(Charset.forName("UTF-8"));

    multipartFile1 = new MockMultipartFile("requestPart", "", "text/plain", content);
    multipartFile2 = new MockMultipartFile("requestPart", "", "text/plain", content);
    multipartRequest = new MockMultipartHttpServletRequest();
    multipartRequest.addFile(multipartFile1);
    multipartRequest.addFile(multipartFile2);
    webRequest = new ServletWebRequest(multipartRequest, new MockHttpServletResponse());
}
项目:spring4-understanding    文件:HandlerMethodInvoker.java   
private Object[] resolveInitBinderArguments(Object handler, Method initBinderMethod,
        WebDataBinder binder, NativeWebRequest webRequest) throws Exception {

    Class<?>[] initBinderParams = initBinderMethod.getParameterTypes();
    Object[] initBinderArgs = new Object[initBinderParams.length];

    for (int i = 0; i < initBinderArgs.length; i++) {
        MethodParameter methodParam = new SynthesizingMethodParameter(initBinderMethod, i);
        methodParam.initParameterNameDiscovery(this.parameterNameDiscoverer);
        GenericTypeResolver.resolveParameterType(methodParam, handler.getClass());
        String paramName = null;
        boolean paramRequired = false;
        String paramDefaultValue = null;
        String pathVarName = null;
        Annotation[] paramAnns = methodParam.getParameterAnnotations();

        for (Annotation paramAnn : paramAnns) {
            if (RequestParam.class.isInstance(paramAnn)) {
                RequestParam requestParam = (RequestParam) paramAnn;
                paramName = requestParam.name();
                paramRequired = requestParam.required();
                paramDefaultValue = parseDefaultValueAttribute(requestParam.defaultValue());
                break;
            }
            else if (ModelAttribute.class.isInstance(paramAnn)) {
                throw new IllegalStateException(
                        "@ModelAttribute is not supported on @InitBinder methods: " + initBinderMethod);
            }
            else if (PathVariable.class.isInstance(paramAnn)) {
                PathVariable pathVar = (PathVariable) paramAnn;
                pathVarName = pathVar.value();
            }
        }

        if (paramName == null && pathVarName == null) {
            Object argValue = resolveCommonArgument(methodParam, webRequest);
            if (argValue != WebArgumentResolver.UNRESOLVED) {
                initBinderArgs[i] = argValue;
            }
            else {
                Class<?> paramType = initBinderParams[i];
                if (paramType.isInstance(binder)) {
                    initBinderArgs[i] = binder;
                }
                else if (BeanUtils.isSimpleProperty(paramType)) {
                    paramName = "";
                }
                else {
                    throw new IllegalStateException("Unsupported argument [" + paramType.getName() +
                            "] for @InitBinder method: " + initBinderMethod);
                }
            }
        }

        if (paramName != null) {
            initBinderArgs[i] =
                    resolveRequestParam(paramName, paramRequired, paramDefaultValue, methodParam, webRequest, null);
        }
        else if (pathVarName != null) {
            initBinderArgs[i] = resolvePathVariable(pathVarName, methodParam, webRequest, null);
        }
    }

    return initBinderArgs;
}
项目:spring-cloud-stream    文件:StreamEmitterAnnotationBeanPostProcessor.java   
@SuppressWarnings({ "rawtypes", "unchecked" })
private void invokeSetupMethodOnToTargetChannel(Method method, Object bean, String outboundName) {
    Object[] arguments = new Object[method.getParameterCount()];
    Object targetBean = null;
    for (int parameterIndex = 0; parameterIndex < arguments.length; parameterIndex++) {
        MethodParameter methodParameter = new SynthesizingMethodParameter(method, parameterIndex);
        Class<?> parameterType = methodParameter.getParameterType();
        Object targetReferenceValue = null;
        if (methodParameter.hasParameterAnnotation(Output.class)) {
            targetReferenceValue = AnnotationUtils.getValue(methodParameter.getParameterAnnotation(Output.class));
        }
        else if (arguments.length == 1 && StringUtils.hasText(outboundName)) {
            targetReferenceValue = outboundName;
        }
        if (targetReferenceValue != null) {
            targetBean = this.applicationContext.getBean((String) targetReferenceValue);
            for (StreamListenerParameterAdapter<?, Object> streamListenerParameterAdapter : this.parameterAdapters) {
                if (streamListenerParameterAdapter.supports(targetBean.getClass(), methodParameter)) {
                    arguments[parameterIndex] = streamListenerParameterAdapter.adapt(targetBean,
                            methodParameter);
                    if (arguments[parameterIndex] instanceof FluxSender) {
                        closeableFluxResources.add((FluxSender) arguments[parameterIndex]);
                    }
                    break;
                }
            }
            Assert.notNull(arguments[parameterIndex], "Cannot convert argument " + parameterIndex + " of " + method
                    + "from " + targetBean.getClass() + " to " + parameterType);
        }
        else {
            throw new IllegalStateException(StreamEmitterErrorMessages.ATLEAST_ONE_OUTPUT);
        }
    }
    Object result;
    try {
        result = method.invoke(bean, arguments);
    }
    catch (Exception e) {
        throw new BeanInitializationException("Cannot setup StreamEmitter for " + method, e);
    }

    if (!Void.TYPE.equals(method.getReturnType())) {
        if (targetBean == null) {
            targetBean = this.applicationContext.getBean(outboundName);
        }
        boolean streamListenerResultAdapterFound = false;
        for (StreamListenerResultAdapter streamListenerResultAdapter : this.resultAdapters) {
            if (streamListenerResultAdapter.supports(result.getClass(), targetBean.getClass())) {
                Closeable fluxDisposable = streamListenerResultAdapter.adapt(result, targetBean);
                closeableFluxResources.add(fluxDisposable);
                streamListenerResultAdapterFound = true;
                break;
            }
        }
        Assert.state(streamListenerResultAdapterFound,
                StreamEmitterErrorMessages.CANNOT_CONVERT_RETURN_TYPE_TO_ANY_AVAILABLE_RESULT_ADAPTERS);
    }
}