javascript
Spring自定义参数解析器
??雖然Spring提供了比較完善的參數(shù)解析器,但是對(duì)于一些特殊的數(shù)據(jù)類型我們還是需要進(jìn)行特殊處理,這樣會(huì)提高代碼的復(fù)雜度,增加冗余的代碼,降低代碼可讀性和可維護(hù)性。所以自定義參數(shù)解析器是一個(gè)很好的解決方案,是的時(shí)候?qū)幋a人員也是透明的,非常方便。
??還有一點(diǎn)需要注意的是,本篇博客自定義參數(shù)解析器使用的方法是通過(guò)繼承AbstractNamedValueMethodArgumentResolver類實(shí)現(xiàn)的,而我們經(jīng)常使用的注解@RequestParam的參數(shù)解析器也是繼承自AbstractNamedValueMethodArgumentResolver類。當(dāng)然還有一種解決方案是通過(guò)實(shí)現(xiàn)HandlerMethodArgumentResolver接口來(lái)實(shí)現(xiàn),但是區(qū)別的是如果通過(guò)HandlerMethodArgumentResolver接口來(lái)實(shí)現(xiàn)的話,在解析器中會(huì)獲取到所有的參數(shù),而我們還需要另外寫(xiě)代碼在一串參數(shù)中的到我們需要處理的參數(shù)再進(jìn)行處理。而通過(guò)繼承AbstractNamedValueMethodArgumentResolver類來(lái)實(shí)現(xiàn)的話,因?yàn)锳bstractNamedValueMethodArgumentResolver類本身就實(shí)現(xiàn)了HandlerMethodArgumentResolver接口,所以我們?cè)趨?shù)解析器中得到的是一個(gè)一個(gè)的參數(shù),處理起來(lái)相對(duì)簡(jiǎn)單。
??本項(xiàng)目是用SpringBoot寫(xiě)的,自定義用于將字符串解析為Date時(shí)間類型的參數(shù)解析器。
1、項(xiàng)目目錄結(jié)構(gòu)
2、RequestDateParam
package com.xyc.argumentresolver.annotation;import com.xyc.argumentresolver.constant.DateFormatPattern;import java.lang.annotation.*;/*** Created by xyc on 2017/7/27 0027.*/ @Documented @Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) public @interface RequestDateParam {String value() default "";DateFormatPattern pattern() default DateFormatPattern.YYYY_MM_DD_HH_MM_SS;boolean required() default true; }3、DateFormatPattern
package com.xyc.argumentresolver.constant;/*** Created by xyc on 2017/7/29 0029.*/ public enum DateFormatPattern {YYYY_MM_DD("yyyy-MM-dd"), YYYY_MM_DD_HH_MM_SS("yyyy-MM-dd hh:mm:ss");private String value;DateFormatPattern(String value) {this.value = value;}public String getValue() {return value;}public void setValue(String value) {this.value = value;} }4、ArgumentResolverApplication
package com.xyc.argumentresolver;import com.xyc.argumentresolver.resolver.RequestDateParamMethodArgumentResolver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import java.util.List;@SpringBootApplication public class ArgumentResolverApplication extends WebMvcConfigurerAdapter {public static void main(String[] args) {SpringApplication.run(ArgumentResolverApplication.class, args);}@Overridepublic void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {argumentResolvers.add(new RequestDateParamMethodArgumentResolver()); //添加自定義參數(shù)解析器} }5、ArgumentResolverController
package com.xyc.argumentresolver.controller;import com.xyc.argumentresolver.annotation.RequestDateParam; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController;import java.util.Date;/*** Created by xyc on 2017/7/27 0027.*/ @RestController @RequestMapping("/argumentResolver") public class ArgumentResolverController {@RequestMapping(value = "/requestDateParamTest", method = RequestMethod.GET)public String requestDateParamTest(@RequestDateParam Date date) {System.out.println(date);return "success value is " + date;} }6、RequestDateParamMethodArgumentResolver
package com.xyc.argumentresolver.resolver;import com.xyc.argumentresolver.annotation.RequestDateParam; import org.springframework.core.MethodParameter; import org.springframework.stereotype.Component; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver;import javax.servlet.ServletException; import java.text.SimpleDateFormat;/*** Created by xyc on 2017/7/29 0029.*/ @Component public class RequestDateParamMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver {/*** 獲取當(dāng)前參數(shù)的注解信息** @param methodParameter 需要被解析的Controller參數(shù)* @return*/@Overrideprotected NamedValueInfo createNamedValueInfo(MethodParameter methodParameter) {RequestDateParam annotation = (RequestDateParam) methodParameter.getParameterAnnotation(RequestDateParam.class);return new NamedValueInfo(annotation.value(), annotation.required(), (String) null);}/*** 在這里進(jìn)行參數(shù)的類型轉(zhuǎn)換** @param s* @param methodParameter 需要被解析的Controller參數(shù)* @param nativeWebRequest 當(dāng)前request* @return 轉(zhuǎn)換后的參數(shù)值* @throws Exception*/@Overrideprotected Object resolveName(String s, MethodParameter methodParameter, NativeWebRequest nativeWebRequest) throws Exception {String content = nativeWebRequest.getParameter(s);if (content == null) {return null;} else {try {RequestDateParam annotation = methodParameter.getParameterAnnotation(RequestDateParam.class);SimpleDateFormat dateFormat = new SimpleDateFormat(annotation.pattern().getValue());return dateFormat.parse(content);} catch (Exception e) {throw new IllegalArgumentException("Date format conversion error", e);}}}/*** 解析器是否支持當(dāng)前參數(shù)** @param methodParameter 需要被解析的Controller參數(shù)* @return*/@Overridepublic boolean supportsParameter(MethodParameter methodParameter) {return methodParameter.hasParameterAnnotation(RequestDateParam.class);}/*** 當(dāng)前參數(shù)值為空且注解的默認(rèn)值也為空則拋出異常** @param name 參數(shù)名* @param parameter 需要被解析的Controller參數(shù)* @throws ServletException*/@Overrideprotected void handleMissingValue(String name, MethodParameter parameter) throws ServletException {throw new MissingServletRequestParameterException(name, parameter.getParameterType().getSimpleName());} }注意:如果是SpringMVC項(xiàng)目,則需要將參數(shù)解析器注冊(cè)到HandlerAdapter中
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"><property name="requestDateParamMethodArgumentResolver"><list><bean class="com.xyc.argumentresolver.resolver.RequestDateParamMethodArgumentResolver" /></list></property><property name="order" value="0" /></bean>github地址:https://github.com/xiayongchao/ArgumentResolver
總結(jié)
以上是生活随笔為你收集整理的Spring自定义参数解析器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: GIT (分布式版本控制系统)
- 下一篇: SpringBoot整合RabbitMQ