Posts

Showing posts from April, 2020

Spring @PropertySource example

In Spring, you can use  @PropertySource  annotation to externalize your configuration to a properties file 1. @PropertySource and @Value A classic example, read a properties file and display with  ${} . config.properties mongodb.url = 1.2.3.4 mongodb.db = hello Copy AppConfigMongoDB package com . app .example. config ; import org . springframework . beans . factory . annotation . Value ; import org . springframework . context . annotation . Bean ; import org . springframework . context . annotation . ComponentScan ; import org . springframework . context . annotation . Configuration ; import org . springframework . context . annotation . PropertySource ; import org . springframework . context . support . PropertySourcesPlaceholderConfigurer ; //... @Configuration @ComponentScan ( basePackages = { "com.app.*" } ) @PropertySource ( "classpath:config.properties" ) public class AppConfigMongoDB { //1.2.3.4 @Value ( "${...

RestTemplate Error Handling

By default, the  RestTemplate  will throw one of these exceptions in case of an HTTP error: HttpClientErrorException  – in case of HTTP status 4xx HttpServerErrorException –  in case of HTTP status 5xx UnknownHttpStatusCodeException –  in case of an unknown HTTP status All these exceptions are extensions of  RestClientResponseException . Obviously, the simplest strategy to add a custom error handling is to wrap the call in a  try/catch  block.  Then, we process the caught exception as we see fit. However,  this simple strategy doesn't scale well  as the number of remote APIs or calls increases. It'd be more efficient if we could implement a reusable error handler for all of our remote calls. Implementing a  ResponseErrorHandler And so, a class that implements  ResponseErrorHandler  will read the HTTP status from the response and either: And so, a class that implements  ResponseErrorH...