我使用的是带有基于头的内容协商的Spring Boot。我有一组端点,它们只对客户端的一个子集可用,其余的都是公共的。我的公共端点注释如下:
@PostMapping(consumes = "application/vnd.com.foo+json", produces = "application/vnd.com.foo+json")
还有我的私人产品,比如
@PostMapping(consumes = "application/vnd.com.foo.private+json", produces = "application/vnd.com.foo.private+json")
我希望公共端点也使用和生成私有mime类型,这样我的私有客户端就可以在所有请求中设置该mime类型。显然,我可以通过在我的所有公共端点上明确指定它来做到这一点:
@PostMapping(consumes = {"application/vnd.com.foo+json", "application/vnd.com.foo.private+json"},
produces = {"application/vnd.com.foo+json", "application/vnd.com.foo.private+json"})
但我想用一种更整洁的方式来做这件事。
是否有某种方法可以将Spring配置为将私有mime类型视为"扩展"公共mime类型?
我可以在我的WebMvcConfigurer bean中配置内容协商:
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.strategies(List.of(new HeaderContentNegotiationStrategy() {
@Override
public List<MediaType> resolveMediaTypes(NativeWebRequest request) throws HttpMediaTypeNotAcceptableException {
List<MediaType> mediaTypes = super.resolveMediaTypes(request);
List<MediaType> publicisedInternalMediaTypes = mediaTypes.stream()
.filter(m -> m.getSubtype().startsWith("vnd.com.foo.private"))
.map(m -> new MediaType(
m.getType(),
m.getSubtype().replace("vnd.com.foo.private", "vnd.com.foo"),
m.getParameters()))
.collect(toList());
mediaTypes.addAll(publicisedInternalMediaTypes);
return mediaTypes;
}
}));
}
到目前为止,这似乎是可行的,但我很想看到一种更标准或更优雅的方式来实现这一点。
编辑:这适用于Accept标头,但不适用于内容类型。
在我的DelegatingWebMvcConfiguration中,我可以覆盖createRequestMappingHandlerMapping((来添加私有消耗,生成映射来添加公共映射。
@Override
protected RequestMappingInfo createRequestMappingInfo(
RequestMapping original, RequestCondition<?> customCondition) {
ExpandedRequestMapping expanded = expandRequestMapping(original);
return super.createRequestMappingInfo(expanded, customCondition);
}
/**
* If the produces or consume fields include a public media type,
* add the corresponding private media type, too.
*/
private ExpandedRequestMapping expandRequestMapping(RequestMapping original) {
return new ExpandedRequestMapping(original);
}
private static String[] expandedMediaTypes(String[] originalArray) {
// If we ever have a controller method that produces or consumes multiple public types,
// then we'll need to change this.
return Arrays.stream(originalArray)
.filter(mediaType -> mediaType.contains(VND_PUBLIC))
.findAny()
.map(publicMediaType -> publicMediaType.replace(VND_PUBLIC, VND_PRIVATE))
.map(privateMediaType -> ArrayUtils.addAll(originalArray, privateMediaType))
.orElse(originalArray);
}
static class ExpandedRequestMapping implements RequestMapping {
private final RequestMapping delegate;
private ExpandedRequestMapping(RequestMapping delegate) {
this.delegate = delegate;
}
@Override
public String[] consumes() {
return expandedMediaTypes(delegate.consumes());
}
@Override
public String[] produces() {
return expandedMediaTypes(delegate.produces());
}
// delegate other methods
}