Klasa SourceHttpMessageConverter nie jest domyślnie zarejestrowana

Ta reguła oznacza użycie javax.xml.transform.Source gdy interfejs SourceHttpMessageConverter klasa jest nie znaleziona. W witrynie Spring Framework 6.0 SourceHttpMessageConverter klasa jest nie nie jest już domyślnie zarejestrowana w Spring MVC lub RestTemplate.

W rezultacie aplikacje internetowe Spring wykorzystujące javax.xml.transform.Source teraz trzeba skonfigurować SourceHttpMessageConverter wyraźnie. Należy zauważyć, że kolejność rejestracji konwertera ma znaczenie. Na przykład kod: SourceHttpMessageConverter powinien powinny być rejestrowane przed konwerterami typu "catch-all", takimi jak MappingJackson2HttpMessageConverter.

Poniższy fragment kodu pokazuje użycie funkcji 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();
                    }
                }  
             

W Spring Framework 6.0, kod kontrolera pozostaje niezmieniony, ale wymagane są dodatkowe kroki konfiguracyjne aby zapewnić jego prawidłowe działanie. Możesz się zarejestrować SourceHttpMessageConverter ręcznie w Configuration kod. Poniżej znajduje się przykład tego przypadku użycia:

            @Configuration
            public class WebConfig implements WebMvcConfigurer{
                @Override
                public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
                    converters.add(new SourceHttpMessageConverter<>());
                }
            }
            

Alternatywnie można skonfigurować SourceHttpMessageConverter w ramach RestTemplate jeśli używasz go do pobierania XML z usług zewnętrznych. Oto przykład takiego przypadku użycia:

            @Bean
            public RestTemplate restTemplate() {
                RestTemplate restTemplate = new RestTemplate();
                restTemplate.getMessageConverters().add(new SourceHttpMessageConverter<>());
                return restTemplate;
            }       
            

Więcej informacji na ten temat zawierają następujące zasoby: