Consistent configurer access in WebMvcConfigurationSupport

Issue: SPR-16017
This commit is contained in:
Juergen Hoeller 2017-09-27 19:00:51 +02:00
parent cc70fdcbeb
commit 40ba95f82e
11 changed files with 161 additions and 98 deletions

View File

@ -39,6 +39,7 @@ import org.springframework.web.context.request.NativeWebRequest;
* {@code MediaTypeFileExtensionResolver} instances. * {@code MediaTypeFileExtensionResolver} instances.
* *
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
* @author Juergen Hoeller
* @since 3.2 * @since 3.2
*/ */
public class ContentNegotiationManager implements ContentNegotiationStrategy, MediaTypeFileExtensionResolver { public class ContentNegotiationManager implements ContentNegotiationStrategy, MediaTypeFileExtensionResolver {
@ -65,6 +66,7 @@ public class ContentNegotiationManager implements ContentNegotiationStrategy, Me
* A collection-based alternative to * A collection-based alternative to
* {@link #ContentNegotiationManager(ContentNegotiationStrategy...)}. * {@link #ContentNegotiationManager(ContentNegotiationStrategy...)}.
* @param strategies the strategies to use * @param strategies the strategies to use
* @since 3.2.2
*/ */
public ContentNegotiationManager(Collection<ContentNegotiationStrategy> strategies) { public ContentNegotiationManager(Collection<ContentNegotiationStrategy> strategies) {
Assert.notEmpty(strategies, "At least one ContentNegotiationStrategy is expected"); Assert.notEmpty(strategies, "At least one ContentNegotiationStrategy is expected");
@ -95,7 +97,7 @@ public class ContentNegotiationManager implements ContentNegotiationStrategy, Me
/** /**
* Find a {@code ContentNegotiationStrategy} of the given type. * Find a {@code ContentNegotiationStrategy} of the given type.
* @param strategyType the strategy type * @param strategyType the strategy type
* @return the first matching strategy or {@code null}. * @return the first matching strategy, or {@code null} if none
* @since 4.3 * @since 4.3
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -85,6 +85,7 @@ import org.springframework.web.context.ServletContextAware;
* extension to a MediaType. You may {@link #setUseJaf suppress} the use of JAF. * extension to a MediaType. You may {@link #setUseJaf suppress} the use of JAF.
* *
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
* @author Brian Clozel
* @since 3.2 * @since 3.2
*/ */
public class ContentNegotiationManagerFactoryBean public class ContentNegotiationManagerFactoryBean
@ -255,8 +256,7 @@ public class ContentNegotiationManagerFactoryBean
if (this.favorPathExtension) { if (this.favorPathExtension) {
PathExtensionContentNegotiationStrategy strategy; PathExtensionContentNegotiationStrategy strategy;
if (this.servletContext != null && !isUseJafTurnedOff()) { if (this.servletContext != null && !isUseJafTurnedOff()) {
strategy = new ServletPathExtensionContentNegotiationStrategy( strategy = new ServletPathExtensionContentNegotiationStrategy(this.servletContext, this.mediaTypes);
this.servletContext, this.mediaTypes);
} }
else { else {
strategy = new PathExtensionContentNegotiationStrategy(this.mediaTypes); strategy = new PathExtensionContentNegotiationStrategy(this.mediaTypes);
@ -269,8 +269,7 @@ public class ContentNegotiationManagerFactoryBean
} }
if (this.favorParameter) { if (this.favorParameter) {
ParameterContentNegotiationStrategy strategy = ParameterContentNegotiationStrategy strategy = new ParameterContentNegotiationStrategy(this.mediaTypes);
new ParameterContentNegotiationStrategy(this.mediaTypes);
strategy.setParameterName(this.parameterName); strategy.setParameterName(this.parameterName);
strategies.add(strategy); strategies.add(strategy);
} }

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.web.servlet.config.annotation; package org.springframework.web.servlet.config.annotation;
import java.util.ArrayList; import java.util.ArrayList;
@ -22,7 +23,6 @@ import java.util.concurrent.Callable;
import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.util.Assert;
import org.springframework.web.context.request.async.CallableProcessingInterceptor; import org.springframework.web.context.request.async.CallableProcessingInterceptor;
import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor; import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor;
@ -82,7 +82,6 @@ public class AsyncSupportConfigurer {
* @param interceptors the interceptors to register * @param interceptors the interceptors to register
*/ */
public AsyncSupportConfigurer registerCallableInterceptors(CallableProcessingInterceptor... interceptors) { public AsyncSupportConfigurer registerCallableInterceptors(CallableProcessingInterceptor... interceptors) {
Assert.notNull(interceptors, "Interceptors are required");
this.callableInterceptors.addAll(Arrays.asList(interceptors)); this.callableInterceptors.addAll(Arrays.asList(interceptors));
return this; return this;
} }
@ -93,7 +92,6 @@ public class AsyncSupportConfigurer {
* @param interceptors the interceptors to register * @param interceptors the interceptors to register
*/ */
public AsyncSupportConfigurer registerDeferredResultInterceptors(DeferredResultProcessingInterceptor... interceptors) { public AsyncSupportConfigurer registerDeferredResultInterceptors(DeferredResultProcessingInterceptor... interceptors) {
Assert.notNull(interceptors, "Interceptors are required");
this.deferredResultInterceptors.addAll(Arrays.asList(interceptors)); this.deferredResultInterceptors.addAll(Arrays.asList(interceptors));
return this; return this;
} }

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.web.servlet.config.annotation; package org.springframework.web.servlet.config.annotation;
import java.util.HashMap; import java.util.HashMap;
@ -32,9 +33,6 @@ import org.springframework.web.accept.PathExtensionContentNegotiationStrategy;
* Creates a {@code ContentNegotiationManager} and configures it with * Creates a {@code ContentNegotiationManager} and configures it with
* one or more {@link ContentNegotiationStrategy} instances. * one or more {@link ContentNegotiationStrategy} instances.
* *
* <p>As of 5.0 you can set the exact strategies to use via
* {@link #strategies(List)}.
*
* <p>As an alternative you can also rely on the set of defaults described below * <p>As an alternative you can also rely on the set of defaults described below
* which can be turned on or off or customized through the methods of this * which can be turned on or off or customized through the methods of this
* builder: * builder:
@ -86,12 +84,14 @@ import org.springframework.web.accept.PathExtensionContentNegotiationStrategy;
* of JAF. * of JAF.
* *
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
* @author Brian Clozel
* @author Juergen Hoeller
* @since 3.2 * @since 3.2
* @see ContentNegotiationManagerFactoryBean
*/ */
public class ContentNegotiationConfigurer { public class ContentNegotiationConfigurer {
private final ContentNegotiationManagerFactoryBean factory = private final ContentNegotiationManagerFactoryBean factory = new ContentNegotiationManagerFactoryBean();
new ContentNegotiationManagerFactoryBean();
private final Map<String, MediaType> mediaTypes = new HashMap<String, MediaType>(); private final Map<String, MediaType> mediaTypes = new HashMap<String, MediaType>();
@ -226,18 +226,32 @@ public class ContentNegotiationConfigurer {
* Set a custom {@link ContentNegotiationStrategy} to use to determine * Set a custom {@link ContentNegotiationStrategy} to use to determine
* the content type to use when no content type is requested. * the content type to use when no content type is requested.
* <p>By default this is not set. * <p>By default this is not set.
* @see #defaultContentType
* @since 4.1.2 * @since 4.1.2
* @see #defaultContentType
*/ */
public ContentNegotiationConfigurer defaultContentTypeStrategy(ContentNegotiationStrategy defaultStrategy) { public ContentNegotiationConfigurer defaultContentTypeStrategy(ContentNegotiationStrategy defaultStrategy) {
this.factory.setDefaultContentTypeStrategy(defaultStrategy); this.factory.setDefaultContentTypeStrategy(defaultStrategy);
return this; return this;
} }
protected ContentNegotiationManager getContentNegotiationManager() throws Exception {
/**
* Build a {@link ContentNegotiationManager} based on this configurer's settings.
* @since 4.3.12
* @see ContentNegotiationManagerFactoryBean#getObject()
*/
protected ContentNegotiationManager buildContentNegotiationManager() {
this.factory.addMediaTypes(this.mediaTypes); this.factory.addMediaTypes(this.mediaTypes);
this.factory.afterPropertiesSet(); this.factory.afterPropertiesSet();
return this.factory.getObject(); return this.factory.getObject();
} }
/**
* @deprecated as of 4.3.12, in favor of {@link #buildContentNegotiationManager()}
*/
@Deprecated
protected ContentNegotiationManager getContentNegotiationManager() throws Exception {
return buildContentNegotiationManager();
}
} }

View File

@ -16,12 +16,10 @@
package org.springframework.web.servlet.config.annotation; package org.springframework.web.servlet.config.annotation;
import java.util.HashMap; import java.util.Collections;
import java.util.Map;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.handler.AbstractHandlerMapping; import org.springframework.web.servlet.handler.AbstractHandlerMapping;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
@ -82,23 +80,30 @@ public class DefaultServletHandlerConfigurer {
this.handler.setServletContext(this.servletContext); this.handler.setServletContext(this.servletContext);
} }
/** /**
* Return a handler mapping instance ordered at {@link Integer#MAX_VALUE} containing the * Return a handler mapping instance ordered at {@link Integer#MAX_VALUE} containing the
* {@link DefaultServletHttpRequestHandler} instance mapped to {@code "/**"}; * {@link DefaultServletHttpRequestHandler} instance mapped to {@code "/**"};
* or {@code null} if default servlet handling was not been enabled. * or {@code null} if default servlet handling was not been enabled.
* @since 4.3.12
*/ */
protected AbstractHandlerMapping getHandlerMapping() { protected SimpleUrlHandlerMapping buildHandlerMapping() {
if (this.handler == null) { if (this.handler == null) {
return null; return null;
} }
Map<String, HttpRequestHandler> urlMap = new HashMap<String, HttpRequestHandler>();
urlMap.put("/**", this.handler);
SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping(); SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
handlerMapping.setUrlMap(Collections.singletonMap("/**", this.handler));
handlerMapping.setOrder(Integer.MAX_VALUE); handlerMapping.setOrder(Integer.MAX_VALUE);
handlerMapping.setUrlMap(urlMap);
return handlerMapping; return handlerMapping;
} }
/**
* @deprecated as of 4.3.12, in favor of {@link #buildHandlerMapping()}
*/
@Deprecated
protected AbstractHandlerMapping getHandlerMapping() {
return buildHandlerMapping();
}
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -78,9 +78,7 @@ public class PathMatchConfigurer {
* <p>By default this is set to "false". * <p>By default this is set to "false".
* @see WebMvcConfigurer#configureContentNegotiation * @see WebMvcConfigurer#configureContentNegotiation
*/ */
public PathMatchConfigurer setUseRegisteredSuffixPatternMatch( public PathMatchConfigurer setUseRegisteredSuffixPatternMatch(Boolean registeredSuffixPatternMatch) {
Boolean registeredSuffixPatternMatch) {
this.registeredSuffixPatternMatch = registeredSuffixPatternMatch; this.registeredSuffixPatternMatch = registeredSuffixPatternMatch;
return this; return this;
} }
@ -106,6 +104,7 @@ public class PathMatchConfigurer {
return this; return this;
} }
public Boolean isUseSuffixPatternMatch() { public Boolean isUseSuffixPatternMatch() {
return this.suffixPatternMatch; return this.suffixPatternMatch;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -36,6 +36,8 @@ import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
*/ */
public class ViewControllerRegistry { public class ViewControllerRegistry {
private ApplicationContext applicationContext;
private final List<ViewControllerRegistration> registrations = new ArrayList<ViewControllerRegistration>(4); private final List<ViewControllerRegistration> registrations = new ArrayList<ViewControllerRegistration>(4);
private final List<RedirectViewControllerRegistration> redirectRegistrations = private final List<RedirectViewControllerRegistration> redirectRegistrations =
@ -43,7 +45,18 @@ public class ViewControllerRegistry {
private int order = 1; private int order = 1;
private ApplicationContext applicationContext;
/**
* Class constructor with {@link ApplicationContext}.
* @since 4.3.12
*/
public ViewControllerRegistry(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Deprecated
public ViewControllerRegistry() {
}
/** /**
@ -96,19 +109,17 @@ public class ViewControllerRegistry {
this.order = order; this.order = order;
} }
protected void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
/** /**
* Return the {@code HandlerMapping} that contains the registered view * Return the {@code HandlerMapping} that contains the registered view
* controller mappings, or {@code null} for no registrations. * controller mappings, or {@code null} for no registrations.
* @since 4.3.12
*/ */
protected AbstractHandlerMapping getHandlerMapping() { protected SimpleUrlHandlerMapping buildHandlerMapping() {
if (this.registrations.isEmpty() && this.redirectRegistrations.isEmpty()) { if (this.registrations.isEmpty() && this.redirectRegistrations.isEmpty()) {
return null; return null;
} }
Map<String, Object> urlMap = new LinkedHashMap<String, Object>(); Map<String, Object> urlMap = new LinkedHashMap<String, Object>();
for (ViewControllerRegistration registration : this.registrations) { for (ViewControllerRegistration registration : this.registrations) {
urlMap.put(registration.getUrlPath(), registration.getViewController()); urlMap.put(registration.getUrlPath(), registration.getViewController());
@ -116,10 +127,24 @@ public class ViewControllerRegistry {
for (RedirectViewControllerRegistration registration : this.redirectRegistrations) { for (RedirectViewControllerRegistration registration : this.redirectRegistrations) {
urlMap.put(registration.getUrlPath(), registration.getViewController()); urlMap.put(registration.getUrlPath(), registration.getViewController());
} }
SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping(); SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
handlerMapping.setOrder(this.order);
handlerMapping.setUrlMap(urlMap); handlerMapping.setUrlMap(urlMap);
handlerMapping.setOrder(this.order);
return handlerMapping; return handlerMapping;
} }
/**
* @deprecated as of 4.3.12, in favor of {@link #buildHandlerMapping()}
*/
@Deprecated
protected AbstractHandlerMapping getHandlerMapping() {
return buildHandlerMapping();
}
@Deprecated
protected void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
} }

View File

@ -53,25 +53,31 @@ import org.springframework.web.servlet.view.tiles3.TilesViewResolver;
*/ */
public class ViewResolverRegistry { public class ViewResolverRegistry {
private ContentNegotiationManager contentNegotiationManager;
private ApplicationContext applicationContext;
private ContentNegotiatingViewResolver contentNegotiatingResolver; private ContentNegotiatingViewResolver contentNegotiatingResolver;
private final List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>(4); private final List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>(4);
private Integer order; private Integer order;
private ContentNegotiationManager contentNegotiationManager;
private ApplicationContext applicationContext; /**
* Class constructor with {@link ContentNegotiationManager} and {@link ApplicationContext}.
* @since 4.3.12
protected void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) { */
public ViewResolverRegistry(ContentNegotiationManager contentNegotiationManager, ApplicationContext context) {
this.contentNegotiationManager = contentNegotiationManager; this.contentNegotiationManager = contentNegotiationManager;
this.applicationContext = context;
} }
protected void setApplicationContext(ApplicationContext applicationContext) { @Deprecated
this.applicationContext = applicationContext; public ViewResolverRegistry() {
} }
/** /**
* Whether any view resolvers have been registered. * Whether any view resolvers have been registered.
*/ */
@ -79,7 +85,6 @@ public class ViewResolverRegistry {
return (this.contentNegotiatingResolver != null || !this.viewResolvers.isEmpty()); return (this.contentNegotiatingResolver != null || !this.viewResolvers.isEmpty());
} }
/** /**
* Enable use of a {@link ContentNegotiatingViewResolver} to front all other * Enable use of a {@link ContentNegotiatingViewResolver} to front all other
* configured view resolvers and select among all selected Views based on * configured view resolvers and select among all selected Views based on
@ -161,7 +166,7 @@ public class ViewResolverRegistry {
* {@link org.springframework.web.servlet.view.tiles3.TilesConfigurer} bean. * {@link org.springframework.web.servlet.view.tiles3.TilesConfigurer} bean.
*/ */
public UrlBasedViewResolverRegistration tiles() { public UrlBasedViewResolverRegistration tiles() {
if (this.applicationContext != null && !hasBeanOfType(TilesConfigurer.class)) { if (!checkBeanOfType(TilesConfigurer.class)) {
throw new BeanInitializationException("In addition to a Tiles view resolver " + throw new BeanInitializationException("In addition to a Tiles view resolver " +
"there must also be a single TilesConfigurer bean in this web application context " + "there must also be a single TilesConfigurer bean in this web application context " +
"(or its parent)."); "(or its parent).");
@ -178,7 +183,7 @@ public class ViewResolverRegistry {
* {@link org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer} bean. * {@link org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer} bean.
*/ */
public UrlBasedViewResolverRegistration freeMarker() { public UrlBasedViewResolverRegistration freeMarker() {
if (this.applicationContext != null && !hasBeanOfType(FreeMarkerConfigurer.class)) { if (!checkBeanOfType(FreeMarkerConfigurer.class)) {
throw new BeanInitializationException("In addition to a FreeMarker view resolver " + throw new BeanInitializationException("In addition to a FreeMarker view resolver " +
"there must also be a single FreeMarkerConfig bean in this web application context " + "there must also be a single FreeMarkerConfig bean in this web application context " +
"(or its parent): FreeMarkerConfigurer is the usual implementation. " + "(or its parent): FreeMarkerConfigurer is the usual implementation. " +
@ -198,7 +203,7 @@ public class ViewResolverRegistry {
*/ */
@Deprecated @Deprecated
public UrlBasedViewResolverRegistration velocity() { public UrlBasedViewResolverRegistration velocity() {
if (this.applicationContext != null && !hasBeanOfType(org.springframework.web.servlet.view.velocity.VelocityConfigurer.class)) { if (!checkBeanOfType(org.springframework.web.servlet.view.velocity.VelocityConfigurer.class)) {
throw new BeanInitializationException("In addition to a Velocity view resolver " + throw new BeanInitializationException("In addition to a Velocity view resolver " +
"there must also be a single VelocityConfig bean in this web application context " + "there must also be a single VelocityConfig bean in this web application context " +
"(or its parent): VelocityConfigurer is the usual implementation. " + "(or its parent): VelocityConfigurer is the usual implementation. " +
@ -214,7 +219,7 @@ public class ViewResolverRegistry {
* prefix and a default suffix of ".tpl". * prefix and a default suffix of ".tpl".
*/ */
public UrlBasedViewResolverRegistration groovy() { public UrlBasedViewResolverRegistration groovy() {
if (this.applicationContext != null && !hasBeanOfType(GroovyMarkupConfigurer.class)) { if (!checkBeanOfType(GroovyMarkupConfigurer.class)) {
throw new BeanInitializationException("In addition to a Groovy markup view resolver " + throw new BeanInitializationException("In addition to a Groovy markup view resolver " +
"there must also be a single GroovyMarkupConfig bean in this web application context " + "there must also be a single GroovyMarkupConfig bean in this web application context " +
"(or its parent): GroovyMarkupConfigurer is the usual implementation. " + "(or its parent): GroovyMarkupConfigurer is the usual implementation. " +
@ -230,7 +235,7 @@ public class ViewResolverRegistry {
* @since 4.2 * @since 4.2
*/ */
public UrlBasedViewResolverRegistration scriptTemplate() { public UrlBasedViewResolverRegistration scriptTemplate() {
if (this.applicationContext != null && !hasBeanOfType(ScriptTemplateConfigurer.class)) { if (!checkBeanOfType(ScriptTemplateConfigurer.class)) {
throw new BeanInitializationException("In addition to a script template view resolver " + throw new BeanInitializationException("In addition to a script template view resolver " +
"there must also be a single ScriptTemplateConfig bean in this web application context " + "there must also be a single ScriptTemplateConfig bean in this web application context " +
"(or its parent): ScriptTemplateConfigurer is the usual implementation. " + "(or its parent): ScriptTemplateConfigurer is the usual implementation. " +
@ -281,11 +286,6 @@ public class ViewResolverRegistry {
this.order = order; this.order = order;
} }
protected boolean hasBeanOfType(Class<?> beanType) {
return !ObjectUtils.isEmpty(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.applicationContext, beanType, false, false));
}
protected int getOrder() { protected int getOrder() {
return (this.order != null ? this.order : Ordered.LOWEST_PRECEDENCE); return (this.order != null ? this.order : Ordered.LOWEST_PRECEDENCE);
@ -300,6 +300,28 @@ public class ViewResolverRegistry {
} }
} }
private boolean checkBeanOfType(Class<?> beanType) {
return (this.applicationContext == null ||
!ObjectUtils.isEmpty(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.applicationContext, beanType, false, false)));
}
@Deprecated
protected boolean hasBeanOfType(Class<?> beanType) {
return !ObjectUtils.isEmpty(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.applicationContext, beanType, false, false));
}
@Deprecated
protected void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) {
this.contentNegotiationManager = contentNegotiationManager;
}
@Deprecated
protected void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
private static class TilesRegistration extends UrlBasedViewResolverRegistration { private static class TilesRegistration extends UrlBasedViewResolverRegistration {
@ -308,6 +330,7 @@ public class ViewResolverRegistry {
} }
} }
private static class VelocityRegistration extends UrlBasedViewResolverRegistration { private static class VelocityRegistration extends UrlBasedViewResolverRegistration {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@ -317,6 +340,7 @@ public class ViewResolverRegistry {
} }
} }
private static class FreeMarkerRegistration extends UrlBasedViewResolverRegistration { private static class FreeMarkerRegistration extends UrlBasedViewResolverRegistration {
public FreeMarkerRegistration() { public FreeMarkerRegistration() {
@ -325,6 +349,7 @@ public class ViewResolverRegistry {
} }
} }
private static class GroovyMarkupRegistration extends UrlBasedViewResolverRegistration { private static class GroovyMarkupRegistration extends UrlBasedViewResolverRegistration {
public GroovyMarkupRegistration() { public GroovyMarkupRegistration() {
@ -333,6 +358,7 @@ public class ViewResolverRegistry {
} }
} }
private static class ScriptRegistration extends UrlBasedViewResolverRegistration { private static class ScriptRegistration extends UrlBasedViewResolverRegistration {
public ScriptRegistration() { public ScriptRegistration() {

View File

@ -246,32 +246,32 @@ public class WebMvcConfigurationSupport implements ApplicationContextAware, Serv
*/ */
@Bean @Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() { public RequestMappingHandlerMapping requestMappingHandlerMapping() {
RequestMappingHandlerMapping handlerMapping = createRequestMappingHandlerMapping(); RequestMappingHandlerMapping mapping = createRequestMappingHandlerMapping();
handlerMapping.setOrder(0); mapping.setOrder(0);
handlerMapping.setInterceptors(getInterceptors()); mapping.setInterceptors(getInterceptors());
handlerMapping.setContentNegotiationManager(mvcContentNegotiationManager()); mapping.setContentNegotiationManager(mvcContentNegotiationManager());
handlerMapping.setCorsConfigurations(getCorsConfigurations()); mapping.setCorsConfigurations(getCorsConfigurations());
PathMatchConfigurer configurer = getPathMatchConfigurer(); PathMatchConfigurer configurer = getPathMatchConfigurer();
if (configurer.isUseSuffixPatternMatch() != null) { if (configurer.isUseSuffixPatternMatch() != null) {
handlerMapping.setUseSuffixPatternMatch(configurer.isUseSuffixPatternMatch()); mapping.setUseSuffixPatternMatch(configurer.isUseSuffixPatternMatch());
} }
if (configurer.isUseRegisteredSuffixPatternMatch() != null) { if (configurer.isUseRegisteredSuffixPatternMatch() != null) {
handlerMapping.setUseRegisteredSuffixPatternMatch(configurer.isUseRegisteredSuffixPatternMatch()); mapping.setUseRegisteredSuffixPatternMatch(configurer.isUseRegisteredSuffixPatternMatch());
} }
if (configurer.isUseTrailingSlashMatch() != null) { if (configurer.isUseTrailingSlashMatch() != null) {
handlerMapping.setUseTrailingSlashMatch(configurer.isUseTrailingSlashMatch()); mapping.setUseTrailingSlashMatch(configurer.isUseTrailingSlashMatch());
} }
UrlPathHelper pathHelper = configurer.getUrlPathHelper(); UrlPathHelper pathHelper = configurer.getUrlPathHelper();
if (pathHelper != null) { if (pathHelper != null) {
handlerMapping.setUrlPathHelper(pathHelper); mapping.setUrlPathHelper(pathHelper);
} }
PathMatcher pathMatcher = configurer.getPathMatcher(); PathMatcher pathMatcher = configurer.getPathMatcher();
if (pathMatcher != null) { if (pathMatcher != null) {
handlerMapping.setPathMatcher(pathMatcher); mapping.setPathMatcher(pathMatcher);
} }
return handlerMapping; return mapping;
} }
/** /**
@ -364,12 +364,7 @@ public class WebMvcConfigurationSupport implements ApplicationContextAware, Serv
ContentNegotiationConfigurer configurer = new ContentNegotiationConfigurer(this.servletContext); ContentNegotiationConfigurer configurer = new ContentNegotiationConfigurer(this.servletContext);
configurer.mediaTypes(getDefaultMediaTypes()); configurer.mediaTypes(getDefaultMediaTypes());
configureContentNegotiation(configurer); configureContentNegotiation(configurer);
try { this.contentNegotiationManager = configurer.buildContentNegotiationManager();
this.contentNegotiationManager = configurer.getContentNegotiationManager();
}
catch (Throwable ex) {
throw new BeanInitializationException("Could not create ContentNegotiationManager", ex);
}
} }
return this.contentNegotiationManager; return this.contentNegotiationManager;
} }
@ -403,11 +398,10 @@ public class WebMvcConfigurationSupport implements ApplicationContextAware, Serv
*/ */
@Bean @Bean
public HandlerMapping viewControllerHandlerMapping() { public HandlerMapping viewControllerHandlerMapping() {
ViewControllerRegistry registry = new ViewControllerRegistry(); ViewControllerRegistry registry = new ViewControllerRegistry(this.applicationContext);
registry.setApplicationContext(this.applicationContext);
addViewControllers(registry); addViewControllers(registry);
AbstractHandlerMapping handlerMapping = registry.getHandlerMapping(); AbstractHandlerMapping handlerMapping = registry.buildHandlerMapping();
handlerMapping = (handlerMapping != null ? handlerMapping : new EmptyHandlerMapping()); handlerMapping = (handlerMapping != null ? handlerMapping : new EmptyHandlerMapping());
handlerMapping.setPathMatcher(mvcPathMatcher()); handlerMapping.setPathMatcher(mvcPathMatcher());
handlerMapping.setUrlPathHelper(mvcUrlPathHelper()); handlerMapping.setUrlPathHelper(mvcUrlPathHelper());
@ -492,11 +486,11 @@ public class WebMvcConfigurationSupport implements ApplicationContextAware, Serv
*/ */
@Bean @Bean
public HandlerMapping defaultServletHandlerMapping() { public HandlerMapping defaultServletHandlerMapping() {
DefaultServletHandlerConfigurer configurer = new DefaultServletHandlerConfigurer(servletContext); DefaultServletHandlerConfigurer configurer = new DefaultServletHandlerConfigurer(this.servletContext);
configureDefaultServletHandling(configurer); configureDefaultServletHandling(configurer);
AbstractHandlerMapping handlerMapping = configurer.getHandlerMapping();
handlerMapping = handlerMapping != null ? handlerMapping : new EmptyHandlerMapping(); HandlerMapping handlerMapping = configurer.buildHandlerMapping();
return handlerMapping; return (handlerMapping != null ? handlerMapping : new EmptyHandlerMapping());
} }
/** /**
@ -911,9 +905,8 @@ public class WebMvcConfigurationSupport implements ApplicationContextAware, Serv
*/ */
@Bean @Bean
public ViewResolver mvcViewResolver() { public ViewResolver mvcViewResolver() {
ViewResolverRegistry registry = new ViewResolverRegistry(); ViewResolverRegistry registry = new ViewResolverRegistry(
registry.setContentNegotiationManager(mvcContentNegotiationManager()); mvcContentNegotiationManager(), this.applicationContext);
registry.setApplicationContext(this.applicationContext);
configureViewResolvers(registry); configureViewResolvers(registry);
if (registry.getViewResolvers().isEmpty()) { if (registry.getViewResolvers().isEmpty()) {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -42,6 +42,7 @@ public class ContentNegotiationConfigurerTests {
private MockHttpServletRequest servletRequest; private MockHttpServletRequest servletRequest;
@Before @Before
public void setup() { public void setup() {
this.servletRequest = new MockHttpServletRequest(); this.servletRequest = new MockHttpServletRequest();
@ -49,9 +50,10 @@ public class ContentNegotiationConfigurerTests {
this.configurer = new ContentNegotiationConfigurer(this.servletRequest.getServletContext()); this.configurer = new ContentNegotiationConfigurer(this.servletRequest.getServletContext());
} }
@Test @Test
public void defaultSettings() throws Exception { public void defaultSettings() throws Exception {
ContentNegotiationManager manager = this.configurer.getContentNegotiationManager(); ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();
this.servletRequest.setRequestURI("/flower.gif"); this.servletRequest.setRequestURI("/flower.gif");
@ -74,7 +76,7 @@ public class ContentNegotiationConfigurerTests {
@Test @Test
public void addMediaTypes() throws Exception { public void addMediaTypes() throws Exception {
this.configurer.mediaTypes(Collections.singletonMap("json", MediaType.APPLICATION_JSON)); this.configurer.mediaTypes(Collections.singletonMap("json", MediaType.APPLICATION_JSON));
ContentNegotiationManager manager = this.configurer.getContentNegotiationManager(); ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();
this.servletRequest.setRequestURI("/flower.json"); this.servletRequest.setRequestURI("/flower.json");
assertEquals(Arrays.asList(MediaType.APPLICATION_JSON), manager.resolveMediaTypes(this.webRequest)); assertEquals(Arrays.asList(MediaType.APPLICATION_JSON), manager.resolveMediaTypes(this.webRequest));
@ -85,7 +87,7 @@ public class ContentNegotiationConfigurerTests {
this.configurer.favorParameter(true); this.configurer.favorParameter(true);
this.configurer.parameterName("f"); this.configurer.parameterName("f");
this.configurer.mediaTypes(Collections.singletonMap("json", MediaType.APPLICATION_JSON)); this.configurer.mediaTypes(Collections.singletonMap("json", MediaType.APPLICATION_JSON));
ContentNegotiationManager manager = this.configurer.getContentNegotiationManager(); ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();
this.servletRequest.setRequestURI("/flower"); this.servletRequest.setRequestURI("/flower");
this.servletRequest.addParameter("f", "json"); this.servletRequest.addParameter("f", "json");
@ -96,7 +98,7 @@ public class ContentNegotiationConfigurerTests {
@Test @Test
public void ignoreAcceptHeader() throws Exception { public void ignoreAcceptHeader() throws Exception {
this.configurer.ignoreAcceptHeader(true); this.configurer.ignoreAcceptHeader(true);
ContentNegotiationManager manager = this.configurer.getContentNegotiationManager(); ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();
this.servletRequest.setRequestURI("/flower"); this.servletRequest.setRequestURI("/flower");
this.servletRequest.addHeader("Accept", MediaType.IMAGE_GIF_VALUE); this.servletRequest.addHeader("Accept", MediaType.IMAGE_GIF_VALUE);
@ -107,7 +109,7 @@ public class ContentNegotiationConfigurerTests {
@Test @Test
public void setDefaultContentType() throws Exception { public void setDefaultContentType() throws Exception {
this.configurer.defaultContentType(MediaType.APPLICATION_JSON); this.configurer.defaultContentType(MediaType.APPLICATION_JSON);
ContentNegotiationManager manager = this.configurer.getContentNegotiationManager(); ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();
assertEquals(Arrays.asList(MediaType.APPLICATION_JSON), manager.resolveMediaTypes(this.webRequest)); assertEquals(Arrays.asList(MediaType.APPLICATION_JSON), manager.resolveMediaTypes(this.webRequest));
} }
@ -115,8 +117,9 @@ public class ContentNegotiationConfigurerTests {
@Test @Test
public void setDefaultContentTypeStrategy() throws Exception { public void setDefaultContentTypeStrategy() throws Exception {
this.configurer.defaultContentTypeStrategy(new FixedContentNegotiationStrategy(MediaType.APPLICATION_JSON)); this.configurer.defaultContentTypeStrategy(new FixedContentNegotiationStrategy(MediaType.APPLICATION_JSON));
ContentNegotiationManager manager = this.configurer.getContentNegotiationManager(); ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();
assertEquals(Arrays.asList(MediaType.APPLICATION_JSON), manager.resolveMediaTypes(this.webRequest)); assertEquals(Arrays.asList(MediaType.APPLICATION_JSON), manager.resolveMediaTypes(this.webRequest));
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -43,23 +43,25 @@ public class DefaultServletHandlerConfigurerTests {
private MockHttpServletResponse response; private MockHttpServletResponse response;
@Before @Before
public void setUp() { public void setup() {
response = new MockHttpServletResponse(); response = new MockHttpServletResponse();
servletContext = new DispatchingMockServletContext(); servletContext = new DispatchingMockServletContext();
configurer = new DefaultServletHandlerConfigurer(servletContext); configurer = new DefaultServletHandlerConfigurer(servletContext);
} }
@Test @Test
public void notEnabled() { public void notEnabled() {
assertNull(configurer.getHandlerMapping()); assertNull(configurer.buildHandlerMapping());
} }
@Test @Test
public void enable() throws Exception { public void enable() throws Exception {
configurer.enable(); configurer.enable();
SimpleUrlHandlerMapping getHandlerMapping = getHandlerMapping(); SimpleUrlHandlerMapping getHandlerMapping = configurer.buildHandlerMapping();
SimpleUrlHandlerMapping handlerMapping = getHandlerMapping; SimpleUrlHandlerMapping handlerMapping = configurer.buildHandlerMapping();
DefaultServletHttpRequestHandler handler = (DefaultServletHttpRequestHandler) handlerMapping.getUrlMap().get("/**"); DefaultServletHttpRequestHandler handler = (DefaultServletHttpRequestHandler) handlerMapping.getUrlMap().get("/**");
assertNotNull(handler); assertNotNull(handler);
@ -75,7 +77,7 @@ public class DefaultServletHandlerConfigurerTests {
@Test @Test
public void enableWithServletName() throws Exception { public void enableWithServletName() throws Exception {
configurer.enable("defaultServlet"); configurer.enable("defaultServlet");
SimpleUrlHandlerMapping handlerMapping = getHandlerMapping(); SimpleUrlHandlerMapping handlerMapping = configurer.buildHandlerMapping();
DefaultServletHttpRequestHandler handler = (DefaultServletHttpRequestHandler) handlerMapping.getUrlMap().get("/**"); DefaultServletHttpRequestHandler handler = (DefaultServletHttpRequestHandler) handlerMapping.getUrlMap().get("/**");
assertNotNull(handler); assertNotNull(handler);
@ -88,6 +90,7 @@ public class DefaultServletHandlerConfigurerTests {
assertEquals("The request was not forwarded", expected, response.getForwardedUrl()); assertEquals("The request was not forwarded", expected, response.getForwardedUrl());
} }
private static class DispatchingMockServletContext extends MockServletContext { private static class DispatchingMockServletContext extends MockServletContext {
private String url; private String url;
@ -99,8 +102,4 @@ public class DefaultServletHandlerConfigurerTests {
} }
} }
private SimpleUrlHandlerMapping getHandlerMapping() {
return (SimpleUrlHandlerMapping) configurer.getHandlerMapping();
}
} }