spring-boot rest controller 使用枚举作为参数,重写反序列化实现任意值转枚举类型
目录
BaseEnum
package com.src.xxx.constant.enums;
public interface BaseEnum<ValueType> {
ValueType getValue();
}
MyEnum
package com.src.xxx.constant.enums;
import com.fasterxml.jackson.annotation.JsonValue;
import com.src.xxx.constant.enums.BaseEnum;
public enum MyEnum implements BaseEnum<Integer> {
Request(34, "请求"),
Response(59, "响应");
private final int value;
private final String describe;
private MyEnum(int value, String describe) {
this.value = value;
this.describe = describe;
}
@Override
public Integer getValue() {
return this.value;
}
@JsonValue
@Override
public String toString() {
return this.describe;
}
}
StringToEnumConverterFactory
package com.src.xxx.configuration.converter;
import com.google.common.collect.Maps;
import com.src.xxx.constant.enums.BaseEnum;
import com.sun.istack.Nullable;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.util.ObjectUtils;
import java.util.Map;
@SuppressWarnings({"rawtypes", "unchecked"})
public final class StringToEnumConverterFactory implements ConverterFactory<String, BaseEnum<String>> {
private static final Map<Class, Converter> CONVERTERS = Maps.newHashMap();
/**
* Get the converter to convert from S to target type T, where T is also an instance of R.
*
* @param targetType the target type to convert to
* @return a converter from S to T
*/
@Override
public <T extends BaseEnum<String>> Converter<String, T> getConverter(Class<T> targetType) {
Converter<String, T> converter = CONVERTERS.get(targetType);
if(converter == null){
converter = new ObjectToEnumConverter(targetType);
CONVERTERS.put(targetType, converter);
}
return converter;
}
static final class ObjectToEnumConverter<E extends BaseEnum> implements Converter<String, E> {
private final Map<String, E> enumMap = Maps.newHashMap();
ObjectToEnumConverter(Class<E> enumType){
E[] enums = enumType.getEnumConstants();
for (E e : enums) {
enumMap.put(e.getValue().toString(), e);
}
}
@Override
@Nullable
public E convert(String source) {
E e = enumMap.get(source);
if(ObjectUtils.isEmpty(e)) {
return null;
}
return e;
}
}
}
FormatterConfig
package com.src.xxx.configuration;
import com.src.xxx.configuration.converter.StringToEnumConverterFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class FormatterConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverterFactory(new StringToEnumConverterFactory());
}
}
DTO
package com.src.xxx.dto.test;
import com.src.xxx.constant.enums.MyEnum;
import lombok.Data;
@Data
public class EnumQueryDTO {
private MyEnum myEnum;
}
package com.src.xxx.dto.test;
import com.src.xxx.constant.enums.MyEnum;
import lombok.Data;
@Data
public class EnumBodyDTO {
private MyEnum myEnum;
}
RestController
package com.src.xxx.controller;
import com.src.xxx.dto.test.EnumBodyDTO;
import com.src.xxx.dto.test.EnumQueryDTO;
import org.springframework.http.ResponseEntity;
@RestController
@RequestMapping("/api/test")
public class TestController {
@GetMapping("/enum")
public ResponseEntity<MyEnum> getEnum(EnumQueryDTO query) {
return ResponseEntity.ok(query.getMyEnum());
}
@PostMapping("/enum")
public ResponseEntity<MyEnum> postEnum(@RequestBody EnumBodyDTO body) {
return ResponseEntity.ok(body.getMyEnum());
}
}
参考
spring-boot rest controller 使用枚举作为参数,重写反序列化实现任意值转枚举类型的更多相关文章
- Spring Boot AOP之对请求的参数入参与返回结果进行拦截处理
Spring Boot AOP之对请求的参数入参与返回结果进行拦截处理 本文链接:https://blog.csdn.net/puhaiyang/article/details/78146620 ...
- Spring Boot的Controller控制层和页面
一.项目实例 1.项目结构 2.项目代码 1).ActionController.Java: package com.example.controller; import java.util.Date ...
- spring boot:使用validator做接口的参数、表单、类中多字段的参数验证(spring boot 2.3.1)
一,为什么要做参数验证? 永远不要相信我们在后端接收到的数据, 1,防止别人通过接口乱刷服务:有些不怀好意的人或机构会乱刷我们的服务,例如:短信接口, 相信大家可能很多人在工作中遇到过这种情况 2,防 ...
- spring boot利用controller来测试写的类
我们在开发spring boot应用程序的时候,往往需要测试某个写好的类,但是在测试的时候发现不太好测试,用Junit等测试框架,总是会报一些问题,大致是找不到配置文件以及无法利用spring创建的对 ...
- Spring Boot之 Controller 接收参数和返回数据总结(包括上传、下载文件)
一.接收参数(postman发送) 1.form表单 @RequestParam("name") String name 会把传递过来的Form表单中的name对应 ...
- Spring Boot学习——Controller的使用
本文主要记录几个注释的使用方法. 1. @Controller : 处理http请求 2. @RequestMapping : 配置URL映射 3. @RestController : 组合注解,sp ...
- spring boot junit controller
MockMvc 来自Spring Test,它允许您通过一组方便的builder类向 DispatcherServlet 发送HTTP请求,并对结果作出断言.请注意,@AutoConfigureMoc ...
- Spring Boot从Controller层进行单元测试
单元测试是程序员对代码的自测,一般公司都会严格要求单元测试,这是对自己代码的负责,也是对代码的敬畏. 一般单元测试都是测试Service层,下面我将演示从Controller层进行单元测试. 无参Co ...
- Spring注解之Controller中获取请求参数及验证使用
1.处理request的uri部分的参数:@PathVariable. 2.处理request header部分的参数:@RequestHeader,@CookieValue@RequestHeade ...
随机推荐
- SCTF 2018_Simple PHP Web
SCTF 2018_Simple PHP Web 进入环境注意观察url http://www.bmzclub.cn:23627/?f=login.php 有点像是文件读取我们尝试读一下/etc/pa ...
- (原创)[C#] 一步一步自定义拖拽(Drag&Drop)时的鼠标效果:(一)基本原理及基本实现
一.前言 拖拽(Drag&Drop),属于是极其常用的基础功能. 无论是在系统上.应用上.还是在网页上,拖拽随处可见.同时拖拽时的鼠标效果也很漂亮,像这样: 这样: 还有这样: 等等等等. 这 ...
- 一行代码让微信小程序支持 cookie
weapp-cookie 一行代码让微信小程序支持 cookie,传送门:github Intro 微信原生的 wx.request 网络请求接口并不支持传统的 Cookie,但有时候我们现有的后端接 ...
- mapreduce统计单词
源代码: WordCountMapper.java: package cn.idcast.mapreduce; import org.apache.hadoop.io.LongWritable; im ...
- SQLite实现数据库的储存2+SQLite数据库可视化工具SQLite Stadio
今日所学 SQLite实现数据库的储存 查看数据库的两种方法 Android 中 SQLite 数据库的查看 - woider - 博客园 SQLite Studio安装教程 [SQLite]可视化工 ...
- VUE-SSR原理和使用
开篇N问 SSR解决了什么问题?SSR存在那些问题?SSR优点缺点是什么如何使用以及原理 自我总结了有如下优势 - SSR利于seo优化,因为实现了在node中解析vue,将实例渲染成一个字符串直接 ...
- 引用nodejs的url模块实现url路由功能
我们在本地创建服务器之后需要写不同的后缀名来访问同一个站点的不同页面,如果不实现路由功能.则每次访问localhost:3000 不论后面写什么 比如localhost:3000/index.loc ...
- Ncrystal Skill设计
在使用allegro时一般都会听说过skill,使用合适的Skill会使事情事半功倍.但是现阶段所能看到的个人白嫖的Skill都有一些通病.所以我才开发符合自己操作习惯的Skill. 当前我们所能找的 ...
- 9. Lab: file system
https://pdos.csail.mit.edu/6.S081/2021/labs/fs.html 1. Large files (moderate) 1.1 要求 Modify bmap() s ...
- Python入门-内置对象函数
1.callable() 查看函数知否可调用,可调用返回True,不可用返回False print("input函数:", callable(input)) #input函数: T ...