This rule flags usage of the
javax.xml.transform.Source
interface when the
SourceHttpMessageConverter class is
not
found.
In Spring Framework 6.0, the
SourceHttpMessageConverter class is
no
longer registered by default in Spring MVC or
RestTemplate.
As a consequence, Spring web applications using
javax.xml.transform.Source now need
to configure
SourceHttpMessageConverter
explicitly. It is important to note that the order of converter registration is important.
For example,
SourceHttpMessageConverter should
be registered before "catch-all" converters like
MappingJackson2HttpMessageConverter.
The following code snippet shows usage of
javax.xml.transform.Source:
@RestController
public class TransformController {
@GetMapping(value = "/transform", produces = MediaType.TEXT_HTML_VALUE)
public String transformXml() throws Exception{
Source xmlSource = new StreamSource(new ClassPathResource("sample.xml").getInputStream());
Source xsltSource = new StreamSource(new ClassPathResource("transform.xslt").getInputStream());
StringWriter writer = new StringWriter();
Result result = new StreamResult(writer);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(xsltSource);
transformer.transform(xmlSource, result);
return writer.toString();
}
}
In Spring Framework 6.0, the controller code remains unchanged, but additional configuration steps are
required to ensure it functions correctly.
You can Register
SourceHttpMessageConverter manually
in Configuration code.
The following is an example of this use case:
@Configuration
public class WebConfig implements WebMvcConfigurer{
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new SourceHttpMessageConverter<>());
}
}
Alternatively, you can configure the
SourceHttpMessageConverter within a
RestTemplate if you're using it to
retrieve XML from external services.
Here is an example of this use case:
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new SourceHttpMessageConverter<>());
return restTemplate;
}
For more information, see the following resources: