Skip to content

Commit

Permalink
Simplify Jackson-related auto-configuration for HATEOAS and Data REST
Browse files Browse the repository at this point in the history
This commit simplifies the Jackson-related auto-configuration that’s
applied when Spring HATEOAS and Spring Data REST are on the classpath.

Previously, Boot used Jackson2HalModule to apply the HAL-related
ObjectMapper configuration to the context’s primary ObjectMapper. This
was to allow HAL-formatted responses to be sent for requests accepted
application/json (see spring-projectsgh-2147). This had the unwanted side-effect of
polluting the primary ObjectMapper with HAL-specific functionality.
Furthermore, Jackson2HalModule is an internal of Spring HATEOAS that
@olivergierke has asked us to avoid using.

This commit replaces the use of Jackson2HalModule with a new approach.
Now, the message converters of any RequestMappingHandlerAdapter beans
are examined and any TypeConstrainedMappingJackson2HttpMessageConverter
instances are modified to support application/json in addition to their
default support for application/hal+json. This behaviour can be disabled
by setting spring.hateoas.use-hal-as-default-json-media-type to false.
This property is named after Spring Data REST’s configuration option
which has the same effect when using Spring Data REST. The new property
replaces the old spring.hateoas.apply-to-primary-object-mapper property.

Previously, when Spring Data REST was on the classpath,
JacksonAutoConfiguration would be switched off resulting in the context
containing multiple ObjectMappers, none of which was primary.

This commit configures RepositoryRestMvcAutoConfiguration to run after
JacksonAutoConfiguration. This gives the latter a chance to create its
primary ObjectMapper before the former adds its ObjectMapper beans to
the context.

Previously, the actuator’s hypermedia support assumed that the
HttpMessageConverters bean would contain every HttpMessageConverter
being used by Spring MVC. When Spring HATEOAS is on the classpath this
isn’t the case as it post-processes RequestMappingHandlerAdapter beans
and adds a TypeConstrainedMappingJackson2HttpMessageConverter to them.
This wasn’t a problem in the past as the primary ObjectMapper, used by a
vanilla MappingJackson2HttpMessageConverter, was configured with Spring
HATEOAS’sJackson2HalModule. Now that this pollution has been tidied up
the assumption described above no longer holds true. MvcEndpointAdvice,
which adds links to the actuator’s json responses, has been updated
to look at the HttpMessageConverters of every
RequestMappingHandlerAdapter when it’s trying to find a converter to
use to write a response with additional hypermedia links.

Integration tests have been added to spring-boot-actuator to ensure
that the changes described above have not regressed the ability to
configure its json output using spring.jackson.* properties (see
spring-projectsgh-1729).

Closes spring-projectsgh-3891
  • Loading branch information
wilkinsona committed Sep 24, 2015
1 parent 028fc04 commit c55900b
Show file tree
Hide file tree
Showing 13 changed files with 402 additions and 111 deletions.
5 changes: 5 additions & 0 deletions spring-boot-actuator/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -302,5 +302,10 @@
<artifactId>spring-data-elasticsearch</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.boot.autoconfigure.hateoas.HypermediaHttpMessageConverterConfiguration;
import org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ServerProperties;
Expand All @@ -53,6 +54,8 @@
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.hateoas.LinkDiscoverer;
import org.springframework.hateoas.config.EnableHypermediaSupport;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.servlet.DispatcherServlet;
Expand All @@ -69,6 +72,7 @@
*
* @author Dave Syer
* @author Stephane Nicoll
* @author Andy Wilkinson
* @see EndpointWebMvcAutoConfiguration
*/
@Configuration
Expand Down Expand Up @@ -193,6 +197,14 @@ public Filter springSecurityFilterChain(HierarchicalBeanFactory beanFactory) {

}

@Configuration
@ConditionalOnClass({ LinkDiscoverer.class })
@Import(HypermediaHttpMessageConverterConfiguration.class)
@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
static class HypermediaConfiguration {

}

static class ServerCustomization implements EmbeddedServletContainerCustomizer,
Ordered {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

Expand Down Expand Up @@ -61,6 +62,7 @@
import org.springframework.util.TypeUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
Expand Down Expand Up @@ -219,7 +221,7 @@ private boolean isActuatorEndpointPath(String path) {
public static class MvcEndpointAdvice implements ResponseBodyAdvice<Object> {

@Autowired
private HttpMessageConverters converters;
private List<RequestMappingHandlerAdapter> handlerAdapters;

private Map<MediaType, HttpMessageConverter<?>> converterCache = new ConcurrentHashMap<MediaType, HttpMessageConverter<?>>();

Expand Down Expand Up @@ -275,11 +277,14 @@ private HttpMessageConverter<Object> findConverter(
if (this.converterCache.containsKey(mediaType)) {
return (HttpMessageConverter<Object>) this.converterCache.get(mediaType);
}
for (HttpMessageConverter<?> converter : this.converters) {
if (selectedConverterType.isAssignableFrom(converter.getClass())
&& converter.canWrite(EndpointResource.class, mediaType)) {
this.converterCache.put(mediaType, converter);
return (HttpMessageConverter<Object>) converter;
for (RequestMappingHandlerAdapter handlerAdapter : this.handlerAdapters) {
for (HttpMessageConverter<?> converter : handlerAdapter
.getMessageConverters()) {
if (selectedConverterType.isAssignableFrom(converter.getClass())
&& converter.canWrite(EndpointResource.class, mediaType)) {
this.converterCache.put(mediaType, converter);
return (HttpMessageConverter<Object>) converter;
}
}
}
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,13 @@
import org.springframework.boot.actuate.health.Status;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.test.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
import org.springframework.boot.test.EnvironmentTestUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockServletContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import static org.junit.Assert.assertEquals;
Expand All @@ -37,6 +40,7 @@
* Tests for {@link EndpointWebMvcAutoConfiguration} of the {@link HealthMvcEndpoint}.
*
* @author Dave Syer
* @author Andy Wilkinson
*/
public class HealthMvcEndpointAutoConfigurationTests {

Expand All @@ -53,12 +57,7 @@ public void close() {
public void testSecureByDefault() throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(SecurityAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class,
JacksonAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class,
TestHealthIndicator.class);
this.context.register(TestConfiguration.class);
this.context.refresh();
Health health = (Health) this.context.getBean(HealthMvcEndpoint.class).invoke(
null);
Expand All @@ -70,25 +69,33 @@ public void testSecureByDefault() throws Exception {
public void testNotSecured() throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(SecurityAutoConfiguration.class,
JacksonAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class,
EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class,
TestHealthIndicator.class);
this.context.register(TestConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.context,
"management.security.enabled=false");
this.context.refresh();
Health health = (Health) this.context.getBean(HealthMvcEndpoint.class).invoke(
null);
assertEquals(Status.UP, health.getStatus());
Health map = (Health) health.getDetails().get(
"healthMvcEndpointAutoConfigurationTests.Test");
Health map = (Health) health.getDetails().get("test");
assertEquals("bar", map.getDetails().get("foo"));
}

@Component
protected static class TestHealthIndicator extends AbstractHealthIndicator {
@Configuration
@ImportAutoConfiguration({ SecurityAutoConfiguration.class,
JacksonAutoConfiguration.class, WebMvcAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class,
EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class })
static class TestConfiguration {

@Bean
public TestHealthIndicator testHealthIndicator() {
return new TestHealthIndicator();
}

}

static class TestHealthIndicator extends AbstractHealthIndicator {

@Override
protected void doHealthCheck(Builder builder) throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.test.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
import org.springframework.boot.test.EnvironmentTestUtils;
Expand Down Expand Up @@ -82,6 +83,7 @@ public void testWebConfiguration() throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(SecurityAutoConfiguration.class,
WebMvcAutoConfiguration.class,
ManagementWebSecurityAutoConfiguration.class,
JacksonAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
Expand Down Expand Up @@ -110,13 +112,7 @@ public void testPathNormalization() throws Exception {
public void testWebConfigurationWithExtraRole() throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(EndpointAutoConfiguration.class,
EndpointWebMvcAutoConfiguration.class, JacksonAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class,
SecurityAutoConfiguration.class,
ManagementWebSecurityAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.register(WebConfiguration.class);
this.context.refresh();
UserDetails user = getUser();
assertTrue(user.getAuthorities().containsAll(
Expand Down Expand Up @@ -155,14 +151,7 @@ public void testDisableIgnoredStaticApplicationPaths() throws Exception {
public void testDisableBasicAuthOnApplicationPaths() throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext());
this.context.register(HttpMessageConvertersAutoConfiguration.class,
JacksonAutoConfiguration.class, EndpointAutoConfiguration.class,
EndpointWebMvcAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class,
SecurityAutoConfiguration.class,
ManagementWebSecurityAutoConfiguration.class,
FallbackWebSecurityAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.register(WebConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.context, "security.basic.enabled:false");
this.context.refresh();
// Just the management endpoints (one filter) and ignores now plus the backup
Expand Down Expand Up @@ -248,6 +237,18 @@ private ResultMatcher springAuthenticateRealmHeader() {
Matchers.containsString("realm=\"Spring\""));
}

@Configuration
@ImportAutoConfiguration({ SecurityAutoConfiguration.class,
WebMvcAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class,
JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class,
FallbackWebSecurityAutoConfiguration.class })
static class WebConfiguration {

}

@EnableGlobalAuthentication
@Configuration
static class AuthenticationConfig {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,26 @@
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.boot.autoconfigure.test.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration;
import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration;
import org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
* Minimal configuration required to run the Actuator with hypermedia.
*
* @author Dave Syer
* @author Andy Wilkinson
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
@Import({ ServerPropertiesAutoConfiguration.class,
@ImportAutoConfiguration({ ServerPropertiesAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class,
EmbeddedServletContainerAutoConfiguration.class,
DispatcherServletAutoConfiguration.class, JacksonAutoConfiguration.class,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/*
* Copyright 2012-2015 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.actuate.endpoint.mvc;

import org.junit.Test;
import org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.ManagementServerPropertiesAutoConfiguration;
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration;
import org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.boot.autoconfigure.test.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
import org.springframework.boot.test.EnvironmentTestUtils;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import static org.hamcrest.Matchers.startsWith;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;

/**
* Integration tests for the Actuator's MVC endpoints.
*
* @author Andy Wilkinson
*/
public class MvcEndpointIntegrationTests {

private AnnotationConfigWebApplicationContext context;

@Test
public void defaultJsonResponseIsNotIndented() throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.register(DefaultConfiguration.class);
MockMvc mockMvc = createMockMvc();
mockMvc.perform(get("/beans")).andExpect(content().string(startsWith("{\"")));
}

@Test
public void jsonResponsesCanBeIndented() throws Exception {
assertIndentedJsonResponse(DefaultConfiguration.class);
}

@Test
public void jsonResponsesCanBeIndentedWhenSpringHateoasIsAutoConfigured()
throws Exception {
assertIndentedJsonResponse(SpringHateoasConfiguration.class);
}

@Test
public void jsonResponsesCanBeIndentedWhenSpringDataRestIsAutoConfigured()
throws Exception {
assertIndentedJsonResponse(SpringDataRestConfiguration.class);
}

private void assertIndentedJsonResponse(Class<?> configuration) throws Exception {
this.context = new AnnotationConfigWebApplicationContext();
this.context.register(configuration);
EnvironmentTestUtils.addEnvironment(this.context,
"spring.jackson.serialization.indent-output:true");
MockMvc mockMvc = createMockMvc();
mockMvc.perform(get("/beans")).andExpect(content().string(startsWith("{\n")));
}

private MockMvc createMockMvc() {
this.context.setServletContext(new MockServletContext());
this.context.refresh();
return MockMvcBuilders.webAppContextSetup(this.context).build();
}

@ImportAutoConfiguration({ JacksonAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class, WebMvcAutoConfiguration.class })
static class DefaultConfiguration {

}

@ImportAutoConfiguration({ HypermediaAutoConfiguration.class,
JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class, WebMvcAutoConfiguration.class })
static class SpringHateoasConfiguration {

}

@ImportAutoConfiguration({ HypermediaAutoConfiguration.class,
RepositoryRestMvcAutoConfiguration.class, JacksonAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class, WebMvcAutoConfiguration.class })
static class SpringDataRestConfiguration {

}

}
Loading

0 comments on commit c55900b

Please sign in to comment.