How to do it...

Let's imagine that, for whatever reason, we want to change our JSON converter to output field names using SNAKE_CASE (all lowercase letters separating words with an underscore).

  1. First, let's create a class holding our configuration for the management context named ManagementConfiguration.java located in the src/main/java/com/example/bookpub directory at the root of our project with the following content:
@ManagementContextConfiguration 
public class ManagementConfiguration  
       implements WebMvcConfigurer { 
  @Override 
  public void configureMessageConverters( 
              List<HttpMessageConverter<?>> converters) { 
    HttpMessageConverter c = new 
MappingJackson2HttpMessageConverter( Jackson2ObjectMapperBuilder.json(). propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CAS). build() ); converters.add(c); } }
  1. We also need to add this class to spring.factories located in the src/main/resources/META-INF directory at the root of our project with the following content:
org.springframework.boot.actuate.autoconfigure.web.ManagementContextConfiguration=com.example.bookpub.ManagementConfiguration 
  1. To avoid our configuration being detected by the component scan for the main application context, we need to exclude it by adding the following to BookPubApplication.java located in the src/main/java/com/example/bookpub directory at the root of our project:
@ComponentScan(excludeFilters =  
    @ComponentScan.Filter( 
        type = FilterType.ANNOTATION,  
        classes = ManagementContextConfiguration.class 
    ) 
) 
  1. To have a separate management context, we need to launch it using a different port, so let's amend application.properties located in the src/main/resources directory at the root of our project with the following content:
management.server.port=8081 
management.endpoints.web.exposure.include=*
  1. Finally, let's start our application by executing ./gradlew clean bootRun and then we can access the /threaddump endpoint by opening our browser and going to http://localhost:8081/actuator/threaddump to see our new configuration take place. The field names of the returned JSON should all be in lowercase and words should be separated using an underscore, or in SNAKE_CASE, as it is called. Alternatively, by going to the http://localhost:8080/books/978-1-78528-415-1 endpoint, we should continue seeing JSON field names in the LOWER_CAMEL_CASE format.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.153.63