gpt4 book ai didi

java - Spring Boot 内容协商配置

转载 作者:行者123 更新时间:2023-11-30 06:05:58 33 4
gpt4 key购买 nike

我在使用 spring-boot 配置内容协商时遇到困难。我想保留大部分默认的 spring-boot 配置。我关注了以下https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc/不是最近的教程。目前,当我发送 application/jsontxt/html 请求时, View 似乎没有得到解析,但是当我打开 @EnableWebMvc 时 它似乎确实得到了解决。以下是我当前的配置。

@Configuration // according to the spring-boot docs this should be enough with spring-boot
//@EnableWebMvc If I enable this content-negotiation seems to work without any configuration, but I loose the default spring-boot configuration
public class MvcConfiguration implements WebMvcConfigurer {


@Bean(name = "jsonViewResolver")
public ViewResolver getJsonViewResolver() {
return new JsonViewResolver();
}


@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
// Simple strategy: only path extension is taken into account
configurer.favorPathExtension(true)
.defaultContentType(MediaType.TEXT_HTML)
.mediaType("html", MediaType.TEXT_HTML)
.mediaType("json", MediaType.APPLICATION_JSON);
}

@Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = newContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
return resolver;
}
}

最佳答案

您没有在内容协商管理器中注册解析器。

请尝试进行以下修改:

@Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager){
ContentNegotiatingViewResolver resolver = newContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
List<ViewResolver> resolvers = new ArrayList<>();
ViewResolver aViewResolver = getJsonViewResolver();
resolvers.add(aViewResolver);
resolver.setViewResolvers(resolvers);
return resolver;
}

关于java - Spring Boot 内容协商配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51346834/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com