Skip to content

Auto-configure codecs in WebFlux server & client #9558

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 3, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright 2012-2017 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.
*/

package org.springframework.boot.autoconfigure.http.codec;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.boot.web.codec.CodecCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.codec.CodecConfigurer;
import org.springframework.http.codec.json.Jackson2JsonDecoder;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.util.MimeType;

/**
* {@link EnableAutoConfiguration Auto-configuration}
* for {@link org.springframework.core.codec.Encoder}s and {@link org.springframework.core.codec.Decoder}s.
* @author Brian Clozel
*/
@Configuration
@ConditionalOnClass(CodecConfigurer.class)
@AutoConfigureAfter(JacksonAutoConfiguration.class)
public class CodecsAutoConfiguration {

@Configuration
@ConditionalOnClass(ObjectMapper.class)
static class JacksonCodecConfiguration {

@Bean
@ConditionalOnBean(ObjectMapper.class)
public CodecCustomizer jacksonCodecCustomizer(ObjectMapper objectMapper) {
return configurer -> {
CodecConfigurer.DefaultCodecs defaults = configurer.defaultCodecs();
defaults.jackson2Decoder(new Jackson2JsonDecoder(objectMapper, new MimeType[0]));
defaults.jackson2Encoder(new Jackson2JsonEncoder(objectMapper, new MimeType[0]));
};
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* Copyright 2012-2017 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.
*/

/**
* Auto-configuration for HTTP codecs.
*/
package org.springframework.boot.autoconfigure.http.codec;
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,12 @@
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration;
import org.springframework.boot.autoconfigure.validation.ValidatorAdapter;
import org.springframework.boot.autoconfigure.web.ConditionalOnEnabledResourceChain;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.codec.CodecCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
Expand All @@ -46,6 +48,7 @@
import org.springframework.format.Formatter;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.CacheControl;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.util.ClassUtils;
import org.springframework.validation.Validator;
import org.springframework.web.reactive.config.DelegatingWebFluxConfiguration;
Expand Down Expand Up @@ -79,7 +82,7 @@
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnClass(WebFluxConfigurer.class)
@ConditionalOnMissingBean({ WebFluxConfigurationSupport.class })
@AutoConfigureAfter(ReactiveWebServerAutoConfiguration.class)
@AutoConfigureAfter({ ReactiveWebServerAutoConfiguration.class, CodecsAutoConfiguration.class })
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
public class WebFluxAutoConfiguration {

Expand All @@ -98,19 +101,23 @@ public static class WebFluxConfig implements WebFluxConfigurer {

private final List<HandlerMethodArgumentResolver> argumentResolvers;

private final List<CodecCustomizer> codecCustomizers;

private final ResourceHandlerRegistrationCustomizer resourceHandlerRegistrationCustomizer;

private final List<ViewResolver> viewResolvers;

public WebFluxConfig(ResourceProperties resourceProperties,
WebFluxProperties webFluxProperties, ListableBeanFactory beanFactory,
ObjectProvider<List<HandlerMethodArgumentResolver>> resolvers,
ObjectProvider<List<CodecCustomizer>> codecCustomizers,
ObjectProvider<ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizer,
ObjectProvider<List<ViewResolver>> viewResolvers) {
this.resourceProperties = resourceProperties;
this.webFluxProperties = webFluxProperties;
this.beanFactory = beanFactory;
this.argumentResolvers = resolvers.getIfAvailable();
this.codecCustomizers = codecCustomizers.getIfAvailable();
this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizer
.getIfAvailable();
this.viewResolvers = viewResolvers.getIfAvailable();
Expand All @@ -123,6 +130,13 @@ public void configureArgumentResolvers(ArgumentResolverConfigurer configurer) {
}
}

@Override
public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
if (this.codecCustomizers != null) {
this.codecCustomizers.forEach(codecCustomizer -> codecCustomizer.customize(configurer));
}
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
* Copyright 2012-2017 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.
*/

package org.springframework.boot.autoconfigure.web.reactive.function.client;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration;
import org.springframework.boot.web.codec.CodecCustomizer;
import org.springframework.boot.web.reactive.function.client.WebClientCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.annotation.Order;
import org.springframework.util.CollectionUtils;
import org.springframework.web.reactive.function.client.WebClient;

/**
* {@link EnableAutoConfiguration Auto-configuration} for {@link WebClient}.
* <p>This will produce a {@link WebClient.Builder} bean with the {@code prototype} scope,
* meaning each injection point will receive a newly cloned instance of the builder.
*
* @author Brian Clozel
* @since 2.0.0
*/
@Configuration
@ConditionalOnClass(WebClient.class)
@AutoConfigureAfter(CodecsAutoConfiguration.class)
public class WebClientAutoConfiguration {

private final WebClient.Builder webClientBuilder;


public WebClientAutoConfiguration(ObjectProvider<List<WebClientCustomizer>> customizerProvider) {
this.webClientBuilder = WebClient.builder();
List<WebClientCustomizer> customizers = customizerProvider.getIfAvailable();
if (!CollectionUtils.isEmpty(customizers)) {
customizers = new ArrayList<>(customizers);
AnnotationAwareOrderComparator.sort(customizers);
customizers.forEach(customizer -> customizer.customize(this.webClientBuilder));
}
}

@Bean
@Scope("prototype")
@ConditionalOnMissingBean
public WebClient.Builder webClientBuilder(List<WebClientCustomizer> customizers) {
return this.webClientBuilder.clone();
}

@Configuration
@ConditionalOnBean(CodecCustomizer.class)
protected static class WebClientCodecsConfiguration {

@Bean
@ConditionalOnMissingBean
@Order(0)
public WebClientCodecCustomizer exchangeStrategiesCustomizer(
List<CodecCustomizer> codecCustomizers) {
return new WebClientCodecCustomizer(codecCustomizers);
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright 2012-2017 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.
*/

package org.springframework.boot.autoconfigure.web.reactive.function.client;

import java.util.List;

import org.springframework.boot.web.codec.CodecCustomizer;
import org.springframework.boot.web.reactive.function.client.WebClientCustomizer;
import org.springframework.web.reactive.function.client.ExchangeStrategies;
import org.springframework.web.reactive.function.client.WebClient;

/**
* {@link WebClientCustomizer} that configures codecs for the HTTP client.
* @author Brian Clozel
* @since 2.0.0
*/
public class WebClientCodecCustomizer implements WebClientCustomizer {

private final List<CodecCustomizer> codecCustomizers;

public WebClientCodecCustomizer(List<CodecCustomizer> codecCustomizers) {
this.codecCustomizers = codecCustomizers;
}

@Override
public void customize(WebClient.Builder webClientBuilder) {
webClientBuilder
.exchangeStrategies(ExchangeStrategies.builder()
.codecs(codecs -> {
this.codecCustomizers.forEach(codecCustomizer -> codecCustomizer.customize(codecs));
}).build());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
Expand Down Expand Up @@ -114,6 +115,7 @@ org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,
org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,15 @@
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfigurationTests.Config;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.boot.web.codec.CodecCustomizer;
import org.springframework.boot.web.reactive.context.GenericReactiveWebApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.ObjectUtils;
Expand All @@ -60,7 +62,9 @@
import org.springframework.web.reactive.result.view.ViewResolver;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

/**
* Tests for {@link WebFluxAutoConfiguration}.
Expand Down Expand Up @@ -105,13 +109,22 @@ public void shouldRegisterCustomHandlerMethodArgumentResolver() throws Exception
.getBean(RequestMappingHandlerAdapter.class);
assertThat((List<HandlerMethodArgumentResolver>) ReflectionTestUtils
.getField(adapter.getArgumentResolverConfigurer(), "customResolvers"))
.contains(
this.context.getBean("firstResolver",
HandlerMethodArgumentResolver.class),
.contains(
this.context.getBean("firstResolver",
HandlerMethodArgumentResolver.class),
this.context.getBean("secondResolver",
HandlerMethodArgumentResolver.class));
}

@Test
public void shouldCustomizeCodecs() throws Exception {
load(CustomCodecCustomizers.class);
CodecCustomizer codecCustomizer =
this.context.getBean("firstCodecCustomizer", CodecCustomizer.class);
assertThat(codecCustomizer).isNotNull();
verify(codecCustomizer).customize(any(ServerCodecConfigurer.class));
}

@Test
public void shouldRegisterResourceHandlerMapping() throws Exception {
load();
Expand Down Expand Up @@ -316,6 +329,15 @@ public HandlerMethodArgumentResolver secondResolver() {

}

@Configuration
protected static class CustomCodecCustomizers {

@Bean
public CodecCustomizer firstCodecCustomizer() {
return mock(CodecCustomizer.class);
}
}

@Configuration
protected static class ViewResolvers {

Expand Down
Loading