Tips Every Spring Boot Developer Should Know

1. Using @ModelAttribute Annotation

I saw several developers using Map<String, String> when there are many request parameters.

Java
 
@GetMapping
public SomeDto getAll(@RequestParam Map<String, String> params)


While there is nothing wrong with it, 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>.

@ModelAttribute annotation can be used to map request parameters to a Java object. The 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.

Java
 
@GetMapping
public SomeDto getAll(@Valid @ModelAttribute 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 time, you want to send the same error response that the underlying service is sending.

Sample Handling

Java
 
@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.contentUTF();
        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. Sometimes 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 sometimes you can avoid it, consider you’re testing only the service layer and the only thing you need is a JPA connection.

In that case, you can use @DataJpaTest annotation that starts JPA components and Repository beans. and use @Import annotation to load the service class itself.

Java
 
@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.

Shell
 
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. The first section is for common properties which are enabled for all the spring profiles. The second section is for integration-test spring profile and the third one is for the prod profile.

 

 

 

 

Top