WebReactiveConfiguration.java 14.9 KB
Newer Older
R
Rossen Stoyanchev 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Copyright 2002-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
16

R
Rossen Stoyanchev 已提交
17 18 19 20 21 22 23
package org.springframework.web.reactive.config;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

24 25
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanInitializationException;
R
Rossen Stoyanchev 已提交
26 27 28 29
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
30 31
import org.springframework.core.codec.ByteBufferDecoder;
import org.springframework.core.codec.ByteBufferEncoder;
32
import org.springframework.core.codec.CharSequenceEncoder;
33
import org.springframework.core.codec.Encoder;
34
import org.springframework.core.codec.ResourceDecoder;
35
import org.springframework.core.codec.StringDecoder;
R
Rossen Stoyanchev 已提交
36 37
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.Formatter;
38 39 40
import org.springframework.format.FormatterRegistry;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
R
Rossen Stoyanchev 已提交
41
import org.springframework.http.MediaType;
42 43 44 45 46 47
import org.springframework.http.codec.DecoderHttpMessageReader;
import org.springframework.http.codec.EncoderHttpMessageWriter;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.http.codec.ResourceHttpMessageWriter;
import org.springframework.http.codec.SseEventHttpMessageWriter;
48 49 50 51
import org.springframework.http.codec.json.Jackson2JsonDecoder;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.http.codec.xml.Jaxb2XmlDecoder;
import org.springframework.http.codec.xml.Jaxb2XmlEncoder;
R
Rossen Stoyanchev 已提交
52
import org.springframework.util.ClassUtils;
53 54
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
R
Rossen Stoyanchev 已提交
55 56 57 58 59 60 61 62
import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder;
import org.springframework.web.reactive.result.SimpleHandlerAdapter;
import org.springframework.web.reactive.result.SimpleResultHandler;
import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver;
import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.reactive.result.method.annotation.ResponseBodyResultHandler;
63
import org.springframework.web.reactive.result.method.annotation.ResponseEntityResultHandler;
R
Rossen Stoyanchev 已提交
64 65 66 67 68 69 70 71 72
import org.springframework.web.reactive.result.view.ViewResolutionResultHandler;
import org.springframework.web.reactive.result.view.ViewResolver;

/**
 * The main class for Spring Web Reactive configuration.
 *
 * <p>Import directly or extend and override protected methods to customize.
 *
 * @author Rossen Stoyanchev
73
 * @since 5.0
R
Rossen Stoyanchev 已提交
74
 */
75
@Configuration
R
Rossen Stoyanchev 已提交
76 77 78
public class WebReactiveConfiguration implements ApplicationContextAware {

	private static final boolean jackson2Present =
79 80
			ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", WebReactiveConfiguration.class.getClassLoader()) &&
			ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", WebReactiveConfiguration.class.getClassLoader());
R
Rossen Stoyanchev 已提交
81

82 83
	private static final boolean jaxb2Present =
			ClassUtils.isPresent("javax.xml.bind.Binder", WebReactiveConfiguration.class.getClassLoader());
84

85 86
	private static final boolean rxJava1Present =
			ClassUtils.isPresent("rx.Observable", WebReactiveConfiguration.class.getClassLoader());
R
Rossen Stoyanchev 已提交
87 88 89 90


	private PathMatchConfigurer pathMatchConfigurer;

91 92 93
	private List<HttpMessageReader<?>> messageReaders;

	private List<HttpMessageWriter<?>> messageWriters;
R
Rossen Stoyanchev 已提交
94 95 96 97 98 99 100 101 102

	private ApplicationContext applicationContext;


	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

103 104 105 106
	protected ApplicationContext getApplicationContext() {
		return this.applicationContext;
	}

R
Rossen Stoyanchev 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194

	@Bean
	public RequestMappingHandlerMapping requestMappingHandlerMapping() {
		RequestMappingHandlerMapping mapping = createRequestMappingHandlerMapping();
		mapping.setOrder(0);
		mapping.setContentTypeResolver(mvcContentTypeResolver());

		PathMatchConfigurer configurer = getPathMatchConfigurer();
		if (configurer.isUseSuffixPatternMatch() != null) {
			mapping.setUseSuffixPatternMatch(configurer.isUseSuffixPatternMatch());
		}
		if (configurer.isUseRegisteredSuffixPatternMatch() != null) {
			mapping.setUseRegisteredSuffixPatternMatch(configurer.isUseRegisteredSuffixPatternMatch());
		}
		if (configurer.isUseTrailingSlashMatch() != null) {
			mapping.setUseTrailingSlashMatch(configurer.isUseTrailingSlashMatch());
		}
		if (configurer.getPathMatcher() != null) {
			mapping.setPathMatcher(configurer.getPathMatcher());
		}
		if (configurer.getPathHelper() != null) {
			mapping.setPathHelper(configurer.getPathHelper());
		}

		return mapping;
	}

	/**
	 * Override to plug a sub-class of {@link RequestMappingHandlerMapping}.
	 */
	protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() {
		return new RequestMappingHandlerMapping();
	}

	@Bean
	public RequestedContentTypeResolver mvcContentTypeResolver() {
		RequestedContentTypeResolverBuilder builder = new RequestedContentTypeResolverBuilder();
		builder.mediaTypes(getDefaultMediaTypeMappings());
		configureRequestedContentTypeResolver(builder);
		return builder.build();
	}

	/**
	 * Override to configure media type mappings.
	 * @see RequestedContentTypeResolverBuilder#mediaTypes(Map)
	 */
	protected Map<String, MediaType> getDefaultMediaTypeMappings() {
		Map<String, MediaType> map = new HashMap<>();
		if (jackson2Present) {
			map.put("json", MediaType.APPLICATION_JSON);
		}
		return map;
	}

	/**
	 * Override to configure how the requested content type is resolved.
	 */
	protected void configureRequestedContentTypeResolver(RequestedContentTypeResolverBuilder builder) {
	}

	/**
	 * Callback for building the {@link PathMatchConfigurer}. This method is
	 * final, use {@link #configurePathMatching} to customize path matching.
	 */
	protected final PathMatchConfigurer getPathMatchConfigurer() {
		if (this.pathMatchConfigurer == null) {
			this.pathMatchConfigurer = new PathMatchConfigurer();
			configurePathMatching(this.pathMatchConfigurer);
		}
		return this.pathMatchConfigurer;
	}

	/**
	 * Override to configure path matching options.
	 */
	public void configurePathMatching(PathMatchConfigurer configurer) {
	}

	@Bean
	public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
		RequestMappingHandlerAdapter adapter = createRequestMappingHandlerAdapter();

		List<HandlerMethodArgumentResolver> resolvers = new ArrayList<>();
		addArgumentResolvers(resolvers);
		if (!resolvers.isEmpty()) {
			adapter.setCustomArgumentResolvers(resolvers);
		}

195
		adapter.setMessageReaders(getMessageReaders());
R
Rossen Stoyanchev 已提交
196
		adapter.setConversionService(mvcConversionService());
197
		adapter.setValidator(mvcValidator());
R
Rossen Stoyanchev 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215

		return adapter;
	}

	/**
	 * Override to plug a sub-class of {@link RequestMappingHandlerAdapter}.
	 */
	protected RequestMappingHandlerAdapter createRequestMappingHandlerAdapter() {
		return new RequestMappingHandlerAdapter();
	}

	/**
	 * Provide custom argument resolvers without overriding the built-in ones.
	 */
	protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
	}

	/**
216 217 218 219
	 * Main method to access message readers to use for decoding
	 * controller method arguments with.
	 * <p>Use {@link #configureMessageReaders} to configure the list or
	 * {@link #extendMessageReaders} to add in addition to the default ones.
R
Rossen Stoyanchev 已提交
220
	 */
221 222 223 224 225 226
	protected final List<HttpMessageReader<?>> getMessageReaders() {
		if (this.messageReaders == null) {
			this.messageReaders = new ArrayList<>();
			configureMessageReaders(this.messageReaders);
			if (this.messageReaders.isEmpty()) {
				addDefaultHttpMessageReaders(this.messageReaders);
R
Rossen Stoyanchev 已提交
227
			}
228
			extendMessageReaders(this.messageReaders);
R
Rossen Stoyanchev 已提交
229
		}
230
		return this.messageReaders;
R
Rossen Stoyanchev 已提交
231 232 233
	}

	/**
234 235 236 237 238
	 * Override to configure the message readers to use for decoding
	 * controller method arguments.
	 * <p>If no message readres are specified, default will be added via
	 * {@link #addDefaultHttpMessageReaders}.
	 * @param messageReaders a list to add message readers to, initially an empty
R
Rossen Stoyanchev 已提交
239
	 */
240
	protected void configureMessageReaders(List<HttpMessageReader<?>> messageReaders) {
R
Rossen Stoyanchev 已提交
241 242 243 244
	}

	/**
	 * Adds default converters that sub-classes can call from
245
	 * {@link #configureMessageReaders(List)}.
R
Rossen Stoyanchev 已提交
246
	 */
247 248 249 250
	protected final void addDefaultHttpMessageReaders(List<HttpMessageReader<?>> readers) {
		readers.add(new DecoderHttpMessageReader<>(new ByteBufferDecoder()));
		readers.add(new DecoderHttpMessageReader<>(new StringDecoder()));
		readers.add(new DecoderHttpMessageReader<>(new ResourceDecoder()));
R
Rossen Stoyanchev 已提交
251
		if (jaxb2Present) {
252
			readers.add(new DecoderHttpMessageReader<>(new Jaxb2XmlDecoder()));
R
Rossen Stoyanchev 已提交
253 254
		}
		if (jackson2Present) {
255
			readers.add(new DecoderHttpMessageReader<>(new Jackson2JsonDecoder()));
R
Rossen Stoyanchev 已提交
256 257 258 259
		}
	}

	/**
260
	 * Override this to modify the list of message readers after it has been
R
Rossen Stoyanchev 已提交
261 262
	 * configured, for example to add some in addition to the default ones.
	 */
263
	protected void extendMessageReaders(List<HttpMessageReader<?>> messageReaders) {
R
Rossen Stoyanchev 已提交
264 265 266
	}

	@Bean
267 268
	public FormattingConversionService mvcConversionService() {
		FormattingConversionService service = new DefaultFormattingConversionService();
R
Rossen Stoyanchev 已提交
269 270 271 272 273 274 275
		addFormatters(service);
		return service;
	}

	/**
	 * Override to add custom {@link Converter}s and {@link Formatter}s.
	 */
276
	protected void addFormatters(FormatterRegistry registry) {
R
Rossen Stoyanchev 已提交
277 278
	}

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
	/**
	 * Return a global {@link Validator} instance for example for validating
	 * {@code @RequestBody} method arguments.
	 * <p>Delegates to {@link #getValidator()} first. If that returns {@code null}
	 * checks the classpath for the presence of a JSR-303 implementations
	 * before creating a {@code OptionalValidatorFactoryBean}. If a JSR-303
	 * implementation is not available, a "no-op" {@link Validator} is returned.
	 */
	@Bean
	public Validator mvcValidator() {
		Validator validator = getValidator();
		if (validator == null) {
			if (ClassUtils.isPresent("javax.validation.Validator", getClass().getClassLoader())) {
				Class<?> clazz;
				try {
					String name = "org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean";
295
					clazz = ClassUtils.forName(name, getClass().getClassLoader());
296 297 298 299 300 301 302
				}
				catch (ClassNotFoundException ex) {
					throw new BeanInitializationException("Could not find default validator class", ex);
				}
				catch (LinkageError ex) {
					throw new BeanInitializationException("Could not load default validator class", ex);
				}
303
				validator = (Validator) BeanUtils.instantiateClass(clazz);
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
			}
			else {
				validator = new NoOpValidator();
			}
		}
		return validator;
	}

	/**
	 * Override this method to provide a custom {@link Validator}.
	 */
	protected Validator getValidator() {
		return null;
	}

R
Rossen Stoyanchev 已提交
319 320 321 322 323 324
	@Bean
	public SimpleHandlerAdapter simpleHandlerAdapter() {
		return new SimpleHandlerAdapter();
	}

	@Bean
325
	public SimpleResultHandler simpleResultHandler() {
R
Rossen Stoyanchev 已提交
326
		return new SimpleResultHandler();
R
Rossen Stoyanchev 已提交
327 328 329
	}

	@Bean
330
	public ResponseEntityResultHandler responseEntityResultHandler() {
R
Rossen Stoyanchev 已提交
331
		return new ResponseEntityResultHandler(getMessageWriters(), mvcContentTypeResolver());
332 333 334 335
	}

	@Bean
	public ResponseBodyResultHandler responseBodyResultHandler() {
R
Rossen Stoyanchev 已提交
336
		return new ResponseBodyResultHandler(getMessageWriters(), mvcContentTypeResolver());
R
Rossen Stoyanchev 已提交
337 338
	}

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
	/**
	 * Main method to access message writers to use for encoding return values.
	 * <p>Use {@link #configureMessageWriters(List)} to configure the list or
	 * {@link #extendMessageWriters(List)} to add in addition to the default ones.
	 */
	protected final List<HttpMessageWriter<?>> getMessageWriters() {
		if (this.messageWriters == null) {
			this.messageWriters = new ArrayList<>();
			configureMessageWriters(this.messageWriters);
			if (this.messageWriters.isEmpty()) {
				addDefaultHttpMessageWriters(this.messageWriters);
			}
			extendMessageWriters(this.messageWriters);
		}
		return this.messageWriters;
	}
	/**
	 * Override to configure the message writers to use for encoding
	 * return values.
	 * <p>If no message readers are specified, default will be added via
	 * {@link #addDefaultHttpMessageWriters}.
	 * @param messageWriters a list to add message writers to, initially an empty
	 */
	protected void configureMessageWriters(List<HttpMessageWriter<?>> messageWriters) {
	}
	/**
	 * Adds default converters that sub-classes can call from
	 * {@link #configureMessageWriters(List)}.
	 */
	protected final void addDefaultHttpMessageWriters(List<HttpMessageWriter<?>> writers) {
		List<Encoder<?>> sseDataEncoders = new ArrayList<>();
		writers.add(new EncoderHttpMessageWriter<>(new ByteBufferEncoder()));
371
		writers.add(new EncoderHttpMessageWriter<>(new CharSequenceEncoder()));
372 373
		writers.add(new ResourceHttpMessageWriter());
		if (jaxb2Present) {
374
			writers.add(new EncoderHttpMessageWriter<>(new Jaxb2XmlEncoder()));
375 376
		}
		if (jackson2Present) {
377
			Jackson2JsonEncoder jacksonEncoder = new Jackson2JsonEncoder();
378 379 380
			writers.add(new EncoderHttpMessageWriter<>(jacksonEncoder));
			sseDataEncoders.add(jacksonEncoder);
		}
381
		writers.add(new SseEventHttpMessageWriter(sseDataEncoders));
382 383 384 385 386 387 388 389
	}
	/**
	 * Override this to modify the list of message writers after it has been
	 * configured, for example to add some in addition to the default ones.
	 */
	protected void extendMessageWriters(List<HttpMessageWriter<?>> messageWriters) {
	}

R
Rossen Stoyanchev 已提交
390 391
	@Bean
	public ViewResolutionResultHandler viewResolutionResultHandler() {
392
		ViewResolverRegistry registry = new ViewResolverRegistry(getApplicationContext());
R
Rossen Stoyanchev 已提交
393 394
		configureViewResolvers(registry);
		List<ViewResolver> resolvers = registry.getViewResolvers();
R
Rossen Stoyanchev 已提交
395
		ViewResolutionResultHandler handler = new ViewResolutionResultHandler(resolvers, mvcContentTypeResolver());
R
Rossen Stoyanchev 已提交
396 397 398 399 400 401 402 403 404 405 406 407
		handler.setDefaultViews(registry.getDefaultViews());
		handler.setOrder(registry.getOrder());
		return handler;

	}

	/**
	 * Override this to configure view resolution.
	 */
	protected void configureViewResolvers(ViewResolverRegistry registry) {
	}

408 409 410 411 412 413 414 415 416 417 418 419 420

	private static final class NoOpValidator implements Validator {

		@Override
		public boolean supports(Class<?> clazz) {
			return false;
		}

		@Override
		public void validate(Object target, Errors errors) {
		}
	}

R
Rossen Stoyanchev 已提交
421
}