SpringBoot实现自定义参数注解

1. 实现WebMvcConfigurationSupport中的addArgumentResolvers方法的复写:

 

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    
    @Override
    protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new NameArgumentResolver());
        super.addArgumentResolvers(argumentResolvers);
    }
}
2. NameArgumentResolver定义如下:
package cn.ok;

import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.lang.annotation.Annotation;

@Service
public class NameArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(Name.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        Annotation[] methodAnnotations = methodParameter.getParameterAnnotations();
        for (Annotation methodAnnotation : methodAnnotations) {
            if (methodAnnotation instanceof Name) {
                Name localToken = (Name) methodAnnotation;
                if ("name".equals(localToken.value())) {
                    if (String.class.isAssignableFrom(methodParameter.getParameterType())) {
                        return "welcom to come to hello word";

                    }
                }
            }

            return null;
        }
        return  "";
    }
}
3.自定义枚举Name如下:
package cn.ok;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

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

    String value() default "name";
}
4.Controller接口如下:
 @RequestMapping(value = "/optional/name", method = { RequestMethod.GET })
    public Object requestName(@Name String name) {
        return name;
    }

5. 返回结果为:

welcom to come to hello word
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值