Spring Boot 自定义 HandlerMethodArgumentResolver 接收 Controller 方法参数

Spring Boot About 1,916 words

自定义注解

指定使用在@RequestMapping标柱的方法参数上。

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyParam {

}

自定义对象

@Data
public class MyParamWrapper {

    private String traceId;

    private String token;

}

自定义 HandlerMethodArgumentResolver

public class MyArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        // MyParam 注解要标注 @Target(ElementType.PARAMETER)
        boolean hasParameterAnnotation = parameter.hasParameterAnnotation(MyParam.class);
        boolean assignable = MyParamWrapper.class.isAssignableFrom(parameter.getParameterType());
        return hasParameterAnnotation && assignable;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

        String traceId = webRequest.getHeader("trace-id");
        String token = webRequest.getHeader("token");

        MyParamWrapper wrapper = new MyParamWrapper();
        if(StringUtils.hasText(traceId)){
            wrapper.setTraceId(traceId);
        }
        if(StringUtils.hasText(token)){
            wrapper.setToken(token);
        }
        return wrapper;
    }
}

注入 HandlerMethodArgumentResolver

@Configuration
public class WebConfig {

    @Bean
    public WebMvcConfigurer getWebMvcConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
                resolvers.add(new MyArgumentResolver());
            }
        };
    }

}

使用

@RestController
public class ResolverController {

    @GetMapping("/argument")
    public String argument(@MyParam MyParamWrapper myParamWrapper) {
        return myParamWrapper.toString();
    }

}
Views: 1,087 · Posted: 2023-02-01

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh