我知道spring有三种策略来判断请求的内容并返回对应的类型。 spring使用这三种策略来进行检测。哪些是
- PathExtension(网址中的文件扩展名)
- 路径参数
- 接受 header
我可以重新排序这些,以便 spring 将首先检查接受 header 吗?就像
- 接受 header
- 路径扩展
- 路径参数
最佳答案
为此,您需要自定义 ContentNegotiationManager
。默认的 ContentNegotiationManagerFactoryBean
具有固定的策略顺序,当您想要自定义顺序时,建议实例化您自己的 ContentNegotiationManager
,就像简单的
new ContentNegotiationManager(strategies);
其中strategies
是按正确顺序排列的策略列表。
但我相信扩展 ContentNegotiationManagerFactoryBean
只需重写创建和排序策略的 afterPropertiesSet
方法会更容易。
public class MyCustomContentNegotiationManagerFactoryBean extends ContentNegotiationManagerFactoryBean {
@Override
public void afterPropertiesSet() {
List<ContentNegotiationStrategy> strategies = new ArrayList<ContentNegotiationStrategy>();
if (!this.ignoreAcceptHeader) {
strategies.add(new HeaderContentNegotiationStrategy());
}
if (this.favorPathExtension) {
PathExtensionContentNegotiationStrategy strategy;
if (this.servletContext != null && !isUseJafTurnedOff()) {
strategy = new ServletPathExtensionContentNegotiationStrategy(
this.servletContext, this.mediaTypes);
}
else {
strategy = new PathExtensionContentNegotiationStrategy(this.mediaTypes);
}
strategy.setIgnoreUnknownExtensions(this.ignoreUnknownPathExtensions);
if (this.useJaf != null) {
strategy.setUseJaf(this.useJaf);
}
strategies.add(strategy);
}
if (this.favorParameter) {
ParameterContentNegotiationStrategy strategy =
new ParameterContentNegotiationStrategy(this.mediaTypes);
strategy.setParameterName(this.parameterName);
strategies.add(strategy);
}
if (this.defaultNegotiationStrategy != null) {
strategies.add(this.defaultNegotiationStrategy);
}
this.contentNegotiationManager = new ContentNegotiationManager(strategies);
}
}
然后你可以在你的 spring 配置中使用这个工厂 bean:
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>
<bean id="contentNegotiationManager" class="com.yourcompany.MyCustomContentNegotiationManagerFactoryBean"/>
基于注解的配置
为了在基于注释的配置中配置 ContentNegotiationManager
,请删除 @EnableWebMvc
注释并扩展 WebMvcConfigurationSupport
或 DelegatingWebMvcConfiguration
> 与您的配置类。然后你想覆盖 mvcContentNegotiationManager
method WebMvcConfigurationSupport
。该方法负责实例化 ContentNegotiationManager
。
不要忘记为重写方法添加@Bean
注释。
关于java - 您可以重新排序 Spring MVC 用于确定请求内容的三种策略吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38147215/