
一,背景
项目里有一个接口需要对外提供,对方的解析方式有不同的方式,一个是使用流行的json格式,另外一个却是老系统,只能用xml格式,但是接口内部的实现逻辑是完全一样的,为了适配更多调用方的需求,就需要将同样的接口数据用两种格式提供出去,总觉得哪儿不对劲儿,写了不好的代码。刚好发现Spring 5.3之后 之后出现的一个新特性——路径后缀匹配,可以支持同一个接口,根据调用方的需求,自动做转换。
二,实现步骤
1,确认当前使用的Spring的版本是5.3及之后的
2,如果是5.3x版本,需要配置
spring:
mvc:
contentnegotiation:
favor-path-extension: true
3,如果是6.x版本可以直接实现 WebMvcConfigurer
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Component
public class PathWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        // 开启路径后缀功能
        configurer.favorPathExtension(true) ;
    }
}4,定义一个接口, 路径中使用.*来做后缀, fmt这段可以随意命名
    @GetMapping("/{name}/fmt.*")
    @ResponseBody
    public Object p1(@PathVariable String name) {
        List<User> userList =  userService.list();
        return userList.stream().filter(u -> name.equals(u.getName()) ).collect(Collectors.toList()) ;
    }5,默认是支持json格式的,如果需要支持xml,需要引入
<dependency>
	<groupId>com.fasterxml.jackson.dataformat</groupId>
	<artifactId>jackson-dataformat-xml</artifactId>
</dependency>6, 请求json格式的结果

7, 请求xml格式的结果

如果对你有帮助,记得点赞关注哟!






![无缝融入,即刻智能[2]:MaxKB内置强大工作流引擎,编排AI工作流程,满足多样化业务需求](https://img-blog.csdnimg.cn/img_convert/6d679b21f14952b3a4e13128f7b5c891.jpeg)












