[英]Choose between 2 different MarshallingHttpMessageConverter instances based on path or parameter
Scenario : 场景 :
In a Spring MVC controller (within a SpringBoot 1.2.5 microservice) I have an endpoint which returns a JAXBElement<?>
which is marshalled to XML via a configured MarshallingHttpMessageConverter
bean. 在Spring MVC控制器(在SpringBoot 1.2.5微服务内)中,我有一个端点,该端点返回JAXBElement<?>
,该端点通过配置的MarshallingHttpMessageConverter
bean编组为XML。 This works perfectly fine and currently does not perform validation against any schemas - it just spits out an XML representation of a domain object. 这工作得很好,并且当前不针对任何模式执行验证-它只是散发出域对象的XML表示形式。
Problem 问题
What I would like to be able to do on a per-request basis is specify whether validation should be performed during marshalling, so I can report any problems to the client - but still have the option to simply marshall with no validation. 我希望根据每个请求执行的操作是指定是否应在编组期间执行验证,以便我可以向客户端报告任何问题-但仍然可以选择不进行验证就简单地编组。 Modifying the underlying Jaxb2Marshaller
to do the validation is no problem, I just set the appropriate schema with setSchema
and it works. 修改底层的Jaxb2Marshaller
进行验证是没有问题的,我只需使用setSchema
设置适当的架构即可,并且可以正常工作。
Given that MarshallingHttpMessageConverter
works with a single marshaller instance that is either configured to validate or not, and content negotiation is based on the accept header, how can I modify the setup to facilitate selective validation per request (based on a query parameter or path) - preferably whilst still relying on Spring's content-negotiation magic to do the 'hard work'? 假设MarshallingHttpMessageConverter
与配置为验证或不验证的单个marshaller实例一起使用,并且内容协商基于accept报头,我如何修改设置以促进每个请求的选择性验证(基于查询参数或路径)-最好是在仍然依靠Spring的内容协商魔术来完成“艰苦工作”的同时?
As a (hopefully temporary) workaround, I have bypassed the auto content-negotiation provided by MarshallingHttpMessageConverter
, instead creating two separate Jaxb2Marshaller
beans, one which validates and one which doesn't, and using them directly within the controller method to marshall to a StringResult
, then returning that as a HttpEntity<String>
. 作为一种(可能是临时的)解决方法,我绕过了MarshallingHttpMessageConverter
提供的自动内容协商,而是创建了两个单独的Jaxb2Marshaller
Bean,一个用于验证,另一个未进行验证,并直接在controller方法中使用它们来编组为StringResult
,然后将其作为HttpEntity<String>
。 More manual steps required, but it works and I can easily switch between validating / not validating based on a request parameter (or whatever). 需要更多的手动步骤,但是它可以工作,我可以轻松地根据请求参数(或其他参数)在验证/不验证之间进行切换。
I won't accept this answer just in case anyone else comes up with a cleaner solution. 万一其他人想出一个更干净的解决方案,我将不会接受这个答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.