2017-08-09 42 views
4

是否有可能有兩個不同的@RestControllers在Springboot 使用不同MappingJackson2HttpMessageConverter? ...或者是在Spring引導應用程序中的所有@RestController通用的MappingJackson2HttpMessageConverter?2 @RestControllers具有不同配置

基本上,目標是使用不同的MappingJackson2HttpMessageConverter,它包含一個不同的Jackson ObjectMapper,它使用Jackson MixIn在第二個控制器中重命名(在Json中)id爲priceId。

到第一控制裝置的呼叫會怎麼做:

http://localhost:8080/controller1/price

{ID: 「ID」,說明: 「說明」}

什麼第二控制裝置的呼叫會做:

http://localhost:8080/controller2/price

{priceId: 「ID」,說明: 「描述」}

問候

@SpringBootApplication 
public class EndpointsApplication { 

public static void main(String[] args) { 
    SpringApplication.run(EndpointsApplication.class, args); 
} 

@Data // Lombok 
@AllArgsConstructor 
class Price { 
    String id; 
    String description; 
} 

@RestController 
@RequestMapping(value = "/controller1") 
class PriceController1 { 

    @GetMapping(value = "/price") 
    public Price getPrice() { 
     return new Price("id", "Description"); 
    } 
} 

@RestController 
@RequestMapping(value = "/controller2") 
class PriceController2 { 

    @GetMapping(value = "/price") 
    public Price getPrice() { 
     return new Price("id", "Description"); 
    } 
} 

} 

GitHub上:

https://github.com/fdlessard/SpringBootEndpoints

+1

請看看https://stackoverflow.com/questions/34728814/spring-boot-with-two-mvc-configurations這篇文章。 – Akash

回答

3

MappingJackson2HttpMessageConverter是與@RestController註釋所有控制器常見,但這種情況有解決辦法。常見的解決方案是將控制器返回的結果包裝到標記類中,並使用自定義和/或使用自定義響應媒體類型。

TypeConstrainedMappingJackson2HttpMessageConverter的樣本用法其中ResourceSupport是標記類。

MappingJackson2HttpMessageConverter halConverter = 
    new TypeConstrainedMappingJackson2HttpMessageConverter(ResourceSupport.class); 
halConverter.setSupportedMediaTypes(Arrays.asList(HAL_JSON)); 
halConverter.setObjectMapper(halObjectMapper); 

您可以根據您的代碼在這裏找到工作的例子: https://github.com/AndreasKl/SpringBootEndpoints

而不是使用PropertyNamingStrategy自定義序列的可用於您的Price傳輸對象。

相關問題