Few things that every Spring boot developer should know.
1. Using objects for request params —
I saw several developers using Map<String, String> when there are many request parameters.
@GetMapping
public SomeDto getAll(@RequestParam Map<String, String> params)
While there is nothing wrong with it, but it misses readability. If another developer wants to know which params are supported, then the developer needs to go through the code and have to find all the params, the hard way. Also, Swagger 2.0 specification does not support Map<String, String> 😞
You can map request parameters to a java object. Java object can have all the request parameters that an api is expecting. This way you can use all the javax validations on the java object.
@GetMapping
public SomeDto getAll(@Valid SomeObject params)
2. When using feign client, use @ControllerAdvice to handle all the unhandled FeignException’s —
It is good to have a global exception handler for all FeignExceptions. Most of the times you want to send the same error response that the under lying service is sending.
Sample handling —
@RequiredArgsConstructor
@ControllerAdvice
public class ExceptionControllerAdvice {private final ObjectMapper mapper;@ExceptionHandler(FeignException.class)
public final ResponseEntity < String > handleFeignException(FeignException fex) {
log.error("Exception from downstream service call - ", fex);
HttpStatus status = Optional.ofNullable(HttpStatus.resolve(fex.status()))
.orElse(HttpStatus.INTERNAL_SERVER_ERROR);
String body = Strings.isNullOrEmpty(fex.contentUTF8()) ? fex.getMessage() : fex.contentUTF8();
return new ResponseEntity < > (
body,
getHeadersWithContentType(body),
status
);
}private MultiValueMap < String, String > getHeadersWithContentType(String body) {
HttpHeaders headers = new HttpHeaders();
String contentType = isValidJSON(body) ? "application/json" : "text/plain";
headers.add(HttpHeaders.CONTENT_TYPE, contentType);
return headers;
}private boolean isValidJSON(String body) {
try {
if (Strings.isNullOrEmpty(body)) return false;
mapper.readTree(body);
return true;
} catch (JacksonException e) {
return false;
}
}
}
3. Some times you can avoid starting the spring application context for Integration tests —
For integration tests, you’ll most likely annotate the tests classes with @SpringBootTest, the problem with this annotation is it will start the whole application context. But some times you can avoid it, consider you’re testing only service layer and only thing you need is JPA connection.
In that times you can use @DataJpaTest annotation that starts JPA components and Repository beans. and use @Import annotation to load the service class itself.
@DataJpaTest(showSql = false)
@Import(TestService.class)
public class ServiceTest {@Autowired
private TestService service;@Test
void testFindAll() {
List<String> values = service.findAll();
assertEquals(1, values.size());
}}
4. If you want you can avoid creating multiple properties files for each spring profile —
If you prefer to have only one configuration (application.yml) file in your project, then you can separate each profile configuration using three dashes.
api.info:
title: rest-serice
description: some description
version: 1.0client.url: http://dev.server---spring.config.activate.on-profile: integration-test
client.url: http://mock-server---spring.config.activate.on-profile: prod
client.url: http://real-server
If you see in the above example, there are three sections, which are separated by three dashes. First section is for common properties which are enabled for all the spring profiles. Second section is for integration-test spring profile and third one is for prod profile.
Thank you for reading this story so far, if you like then please share with your friends and colleagues.
If you have knowledge, let others light their candles in it. — Margaret Fuller