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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • SQL Phenomena for Developers
  • Why Camel K?
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project

Trending

  • Understanding the Shift: Why Companies Are Migrating From MongoDB to Aerospike Database?
  • The Perfection Trap: Rethinking Parkinson's Law for Modern Engineering Teams
  • Advancing Robot Vision and Control
  • A Guide to Auto-Tagging and Lineage Tracking With OpenMetadata
  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
17.7K 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
  • Why Camel K?
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!