DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • SQL Phenomena for Developers
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project

Trending

  • Stateless JWT Auth Microservice Architecture With Spring Boot 3 and Redis Sentinel
  • Chaos Engineering Has a Blind Spot. Agentic AI Lives in It.
  • A Deep Dive into Tracing Agentic Workflows (Part 1)
  • Build Self-Managing Data Pipelines With an LLM Agent
  1. DZone
  2. Coding
  3. Frameworks
  4. Tips Every Spring Boot Developer Should Know

Tips Every Spring Boot Developer Should Know

Let's discuss four important tips that every Spring Boot developer should be aware of as they're working with their perspective programs.

By 
Hari Tummala user avatar
Hari Tummala
·
Aug. 05, 21 · Opinion
Likes (16)
Comment
Save
Tweet
Share
18.0K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Spring Framework Spring Boot dev

Published at DZone with permission of Hari Tummala. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • SQL Phenomena for Developers
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook