SpringBoot REST API best practices
SpringBoot3 and Records
- SivaLabs - Using Java Records with Spring Boot 3
- Spring Boot and Java 16 Records (ashishtechmill.com)
- Using Java Records with JPA | Baeldung
REST API reads intros
- All you need to know..https://www.tutorialspoint.com/spring_boot/index.htm
- https://codeburst.io/spring-boot-rest-microservices-best-practices-2a6e50797115
- @progressive coder
Validation
Controller advice
- https://reflectoring.io/spring-boot-exception-handling/
- https://dzone.com/articles/global-exception-handling-with-controlleradvice
Paging
Testing
- https://rieckpil.de/guide-to-testing-spring-boot-applications-with-mockmvc/
- https://reflectoring.io/spring-boot-web-controller-test/
- How to test log statements in Spring
RestTemplate
- https://www.concretepage.com/spring-boot/spring-boot-rest-example#Client-RestTemplate
-
test the REST Clients of your Spring Boot Application with @RestClientTest
RestTemplateBuilder
Error Handling
- https://hellokoding.com/spring-resttemplate-error-handling/
- https://www.baeldung.com/spring-rest-template-error-handling
- https://newbedev.com/spring-resttemplate-exception-handling
HATEOAS
- How to Build Hypermedia API with Spring HATEOAS
- Spring HATEOAS - Adding Pagination Links To RESTful API
- PagedModel using PagedResourcesAssembler
REACTIVE
- https://callistaenterprise.se/blogg/teknik/2020/05/24/blog-series-reactive-programming/
- https://dzone.com/articles/project-reactor-reactive-programming-with-spring-p
SPRING AOP
- Auditing infrastructure for your app using Spring AOP, Custom annotations and Reflection
- https://www.baeldung.com/spring-aop-annotation
- https://howtodoinjava.com/spring-aop-tutorial/
SPRING EVENTS
Consumer-Driven Contract with Pact
Spring Integration
- Introduction to Spring Integration | Baeldung
- Spring Integration Tutorial for Microservice Communication | Toptal
- Spring Integration Kafka Tutorial - Examples Java Code Geeks - 2022
Spring for Apache Kafka
Constructor vs Setter/Field DI
- The IoC container makes sure that all the arguments provided in the constructor are available before passing them into the constructor.
- Constructor injection helps us to identify if our bean is dependent on too many other objects.
- Constructor injection simplifies writing unit tests. Mockito, we can create mock objects that we can then pass into the constructor.
- Constructor injection helps in creating immutable objects. With setter injection, it’s possible to inject the dependency after creation, thus leading to mutable objects which, among other things, may not be thread-safe in a multi-threaded environment and are harder to debug due to their mutability.
- https://reflectoring.io/constructor-injection/
ServerLess
Serverless applications take advantage of modern cloud computing capabilities and abstractions to let you focus on logic rather than on infrastructure. In a serverless environment, you can concentrate on writing application code while the underlying platform takes care of scaling, runtimes, resource allocation, security, and other “server” specifics.
- https://medium.com/@BoweiHan/an-introduction-to-serverless-and-faas-functions-as-a-service-fb5cec0417b2
- https://spring.io/serverless
- https://spring.io/projects/spring-cloud-function
- Spring Cloud Function (building and running from the core)
- Spring Cloud Function Reference Documentation
- https://www.baeldung.com/spring-cloud-function
- https://medium.com/monstar-lab-bangladesh-engineering/developing-server-less-application-with-spring-boot-eea3a761c1d3
- Introduction to Serverless Applications
- Azure + Spring Boot = Serverless
- serverless-examples
Springboot Azure
Spring Cloud Azure is an open-source project that provides seamless Spring integration with Azure services. It gives developers a Spring-idiomatic way to connect and consume Azure services, with only need few lines of configuration and minimal code changes.
- https://www.infoq.com/articles/azure-spring-boot-serverles-dubois/
- https://spring.io/projects/spring-cloud-azure
- https://azure.microsoft.com/en-us/services/spring-cloud/#features
- Secure a Java web app using the Spring Boot Starter for Azure Active Directory
- Spring on Azure integration documentation
- https://www.baeldung.com/spring-boot-azure
- Getting started with Spring Cloud Function in Azure
- https://dzone.com/articles/spring-cloud-function-in-azure
Why SpringBoot Servless and Functions on Azure
Microsoft invests more than USD1 billion annually on cybersecurity research and development. Microsoft seems to prove over and over again its focus on cloud and the Java ecosystem is the new normal.
- https://www.infoq.com/articles/azure-spring-boot-serverles-dubois/
- https://azure.microsoft.com/en-us/services/spring-cloud/#overview
- https://azure.microsoft.com/en-us/free/
SpringBoot Reactive guide
WebFlux and Functional EndPoints: need for a non-blocking web stack to handle concurrency with a small number of threads and scale with fewer hardware resources.
- https://www.baeldung.com/spring-reactive-guide
- https://www.baeldung.com/spring-server-sent-events
- https://www.baeldung.com/spring-webflux
- https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html
- Functional Endpoints
- https://www.baeldung.com/spring-5-functional-web
- How to Build Real-Time Notification Service Using Server-Sent Events
- Head-First Reactive Workshop
Spring and Paging
- https://www.baeldung.com/rest-api-pagination-in-spring
- https://www.baeldung.com/spring-data-jpa-pagination-sorting
- https://springframework.guru/spring-boot-pagination/
- https://howtodoinjava.com/spring-boot2/pagination-sorting-example/
Spring Boot Version
Controller Advice, mulitple handlers, exception handling vnd
To reduce the applicable classes down by package
- Global Exception Handling With @ControllerAdvice
- Error handling with @Transactional
- @SneakyThrows
- Complete Guide to Exception Handling in Spring Boot
- Exception Handling with the Spring 3.2 @ControllerAdvice Annotation at DZone
- Springboat Zalando problem
- Zalando Spring Web from the source
- Problem builder
- The JSON Problem RFC 7807 to the rescue
- SpringBoot exception handling Bealdung january 2021
- In Spring HATEOAS, you can return a VndError
Validation with Spring
- Spring MVC Custom Validator Example
- Spring MVC Validator and @InitBinder
- Validation using Spring's Validator interface
- Rest API and handling multilevel validation exceptions
- Handling JPA validation exceptions and stackoverflow
- Both worlds JSR303 and SB validation
- Multiple initbinders
- MockMvc and unit testing custom validators
- Problem JSON or VND.ERROR?
Serve Static Resources with Spring
Spring Boot comes with a pre-configured implementation of ResourceHttpRequestHandler to facilitate serving static resources. By default, this handler serves static content from any of /static, /public, /resources, and /META-INF/resources directories that are on the classpath. Since src/main/resources is typically on the classpath by default, we can place any of these directories there.
- https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-config-static-resources
- https://zetcode.com/spring/resourcehandlerregistry/
- https://www.baeldung.com/spring-mvc-static-resources
Spring DI patterns
There are three ways Spring lets you declare the dependencies of your class using annotations. Field injection (the bad), Setter injection (the ugly) and finally Constructor injection (the good).... why... read...
- The Good, The Bad, and The Ugly
- Why to use @AllArgsConstructor and @NoArgsConstructor together over an Entity?
Add Proxy to RestTemplate
When the server is configured in system property or JVM starting argument, it impacts the overall application. HTTP Proxy server for each RestTemplate can be configured for SimpleClientHttpRequestFactory which is a default implementation of ClientHttpRequestFactory interface.
- Proxies With RestTemplate | Baeldung
- java how - Using RestTemplate, how to send the request to a proxy first so I can use my junits with JMeter? - Stack overflow
- 33. Calling REST services (spring.io)
Jackson serialization
Jackson ObjectMapper and MappingJackson2HttpMessageConverter
- Customizing HttpMessageConverters with Spring Boot and Spring MVC - DZone Java
- java - Correct JSON REST Controller by Spring - Stack Overflow
- Http Message Converters with the Spring Framework | Baeldung
- Serialization and Deserialization Issues in Spring REST | End Point
- Spring Boot: Customize the Jackson ObjectMapper | Baeldung
- java how - Can you configure Spring controller specific Jackson deserialization? - Stack overflow
- 54. Spring MVC
- 5 ways to customize Spring MVC JSON/XML output Software Engineering Blog (mostafa-asg.github.io)
To have different deserialization configurations you must have different ObjectMapper instances but out of the box Spring uses MappingJackson2HttpMessageConverter which is designed to use only one instance.
Functional Programming patterns with Java8 Lambda's
- DZone Learn more about functional programming patterns in this tutorial on writing simpler, cleaner code.
- DZone How to Reuse Java Streams
- storing the results of expensive function calls and returning the cached result when the same inputs occur again.
- Sneakily Throwing Exceptions in Lambda Expressions in Java
- DZone Sneakily Throwing Exceptions in Lambda Expressions
- Lombok Sneakythrows and lamdba
ClientHttpRequest Interceptor
Spring provides the ClientHttpRequest Interceptor interface, which can intercept requests and modify them or enhance the corresponding information before they are sent to the server.
- Spring RestTemplate uses interceptors to configure HTTP request headers (programmer.group)
- Spring REST Interceptor - ClientHttpRequestInterceptor Example (howtodoinjava.com)
- Adding JWT Authorization tokens
- java how - Using RestTemplate, how to send the request to a proxy first so I can use my junits with JMeter? - Stack overflow
- Proxies With RestTemplate | Baeldung
- Log your RestTemplate Request and Response without destroying the body | Object Partners
- BeanFactoryAnnotationUtils.qualifiedBeanOfType
- java - Using ApplicationContext inside @Configuration class - Stack Overflow
RestTemplate Error Handling
- https://attacomsian.com/blog/spring-boot-resttemplate-error-handling
- https://www.baeldung.com/spring-rest-template-error-handling
RestController PreHandle logging
- Spring - Log Incoming Requests | Baeldung
- https://www.baeldung.com/spring-http-logging#spring-built-in-request-logging
- https://www.baeldung.com/spring-http-logging#1-configure-spring-boot-application
- java how - Spring Boot - How to log all requests and responses with exceptions in single place? - Stack overflow
- spring - How to register a filter to one @RequestMapping method only? - Stack overflow
- How to log validation errors in Spring boot application - Stack Overflow
Extend CommonsRequestLoggingFilter and overwrite shouldNotFilter method like described here
SpringBoot Security and JWT
- Spring Security JWT in Spring Boot 2
- Spring MVC Custom Validator Example
- https://bbenson.co/post/spring-validations-with-examples/
- https://stackoverflow.com/questions/44755789/spring-validation-how-to-retrieve-errors-rejectvalue-in-my-contoller
- errors.reject or errors.rejectvalue
- binder.setValidator(eventValidator) replaces other registered validators. Change to binder.addValidators(eventValidator);
- Hooking Into the Spring Bean Lifecycle (reflectoring.io)
Transactions and ACID
@Transactional only rolls back transactions for unchecked exceptions. For checked exceptions and their subclasses, it commits data. So although an exception is raised here, because it's a checked exception, Spring ignores it and commits the data to the database, making the system inconsistent.
- spring-transactional-propagation-isolation
- Hibernate Entity Lifecycle | Baeldung
- A Word on Spring @Transactional and Exceptions - DZone Java
Javers and Springboot
When dealing with mutable data we usually have only the last state of an entity stored in a database. Fortunately, we have great tools like JaVers. JaVers is an audit log framework that helps to track changes of entities in the application.
- Using JaVers for Data Model Auditing in Spring Data
- Spring integration from the source
- Javers Springboot starter
- Example on github
BPMN2.0 and Springboot
- https://www.process.st/bpmn-tutorial/
- https://www.baeldung.com/flowable
- https://wwv.flowable.com/open-source/docs/bpmn/ch05-Spring/
- https://dzone.com/articles/running-spring-boot-application-with-embedded-camu
- https://medium.com/holisticon-consultants/batch-processing-with-camunda-1df2fd2776ea
- https://docs.camunda.org/get-started/spring-boot/
Deserialize JSON from Springboot resource file
- Baeldung Object mapper Baeldung
- Example of deserialize from JSON
- Reading files from Spring Boot resources
ObjectMapper objectMapper = new ObjectMapper();
Employee employee = objectMapper.readValue(new ClassPathResource( "testcase/employee.json").getFile(), Employee.class);
Spring Boot and Multi-Threading
Multi-threading is similar to multitasking, but enables the processing of executing multiple threads simultaneously, rather than multiple processes. The CompletableFuture, introduced in Java 8, provides an easy way to write asynchronous, non-blocking and multi-threaded code.
- Multi-Threading in Spring Boot using CompletableFuture
- Processing Results of Asynchronous Computations
- Scheduling a task in Java within a CompletableFuture
- HOW TO USE COMPLETABLEFUTURE IN SPRINGBOOT 2
- CompletableFuture Timeouts in Java DZone
- Asynchronous timeouts with CompletableFutures in Java 8 and Java 9
- GITHUB example how to deal timeouts with Java 9 orTimeout
Autoconfiguration
@Conditional (since version 4.0) annotation and beans, the basis for everything Spring Boot does. A Spring application context (all the framework support your application needs, like databases, JMS, MongoDB, Web support and REST) contains an object graph that makes up all the beans that our application needs at runtime. Spring's @Conditional annotation allows us to define conditions under which a certain bean is included in that object graph. Anywhere we define a Spring bean, we can optionally add a condition. Only if this condition is satisfied will the bean be added to the application context. External libraries can contain conditional beans. Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added.
- Create a Custom Auto-Configuration with Spring Boot
- Conditional Beans with Spring Boot
- How autoconfiguration works
- Again
- Spring boot troubleshooting auto-configuration IMPORTANT!!!
- How Spring Boot's Autoconfigurations Work
- AUTOCONFIGURATION CONDITIONS EVALUATION REPORT
Final Answer: What is Spring Boot?
Spring Boot is just a couple of AutoConfigurations classes (== normal Spring @Configurations), that create @Beans for you if certain @Conditions are met.
Three of the most important conditions are
-
@ConditionalOnClass. Checking for dependencies or rather specific classes of dependencies (think: Tomcat, HikariCP, etc).
-
@ConditionalOnProperty. Self-explanatory.
-
@ConditionalOnMissingBean. If the user specified his own, e.g. DataSource, already, then Spring Boot won't try to create its auto-configured one.
Report Output
The auto-configuration report contains information about the classes that Spring Boot found on the classpath and configured automatically. It also shows information about classes that are known to Spring Boot but were not found on the classpath.
And, because we've set debug=true, then we see it in our output:
================== CONDITIONS EVALUATION REPORT ============================ Positive matches: ----------------- AopAutoConfiguration matched: - @ConditionalOnClass found required classes
JMeter and SpringBoot REST services
It is important to ensure effective performance for software applications, and software testing is often required to ensure that the application runs without any failures. This blog on JMeter will provide in-depth knowledge about this load testing tool for analyzing and measuring the performance in the following sequence.
- DZone JMeter Tutorial for Beginners
- Baeldung, performance testing with JMeter
- Configure Jenkins to Run and Show JMeter Tests
- Testing Microservices With JMeter
- mutual two way ssl
- How to use windows certificate store
- user defined variables
- keystore configurations
- REST API Testing with JMeter (step by step)
- Building a Web Test Plan
- JMeter Tutorial: Testing REST Web Services
- How to Load Test: A developer's guide to performance testing
Spring the ultimate guides
Whatever you're building, these guides are designed to get you productive as quickly as possible – using the latest Spring project releases and techniques as recommended by the Spring team.
All the Spring Guides Together
SpringBoot Milestones
- Spring Projects and versions
- Track the project stack with JavaTpoint
- JournalDev updates on Springboot
- JavaTpoint and technical interviews
- Spring Interview Questions and Answers
Spring, Swagger uploading files
-
Manage upload/download of files using REST and Spring Boot at masterspringboot.com
- Handling File Upload Exceptions
Derived Query Methods in Spring
Spring Data JPA leverages this idea in the form of a method naming convention.
So what is the entity fetching strategy anyway?
When JPA loads an entity, it also loads all the EAGER or “join fetch” associations too. As long as the persistence context is opened, navigating the LAZY association results in fetching those as well, through additionally executed queries.Planning your fetching strategy from the very beginning, and adjusting it all along the development cycle isn’t a “premature optimization”; it’s just a natural part of any ORM design.
- Read
- The best way to handle the LazyInitializationException
- Understanding JPA/Hibernate Persistence Context
The LazyInitializationException
is undoubtedly one of the most common exceptions you can get when using Hibernate. Unfortunately, JPA 1.0 decided that @ManyToOne
and @OneToOne
should default to FetchType.EAGER
, so now you have to explicitly mark these two associations as FetchType.LAZY
:
The solution, DTO projections with Spring Data Projections and Open Projections and the most beautiful Dynamic Projections
- Dynamic Projects on Spring Data JPA from the source
- SPRING DATA JPA PROJECTIONS – 5 WAYS TO RETURN CUSTOM RESPONSE
- Partial Data Update with Spring Data
- JPA join types
Spring Data JPA Specification
Spring Data JPA was created primarily to allow easy query creation with query generation by method name. However, sometimes, we need to create complex queries and cannot take advantage of a query generator. The Spring Data JPA provides a repository programming model that starts with an interface per managed domain object. Defining these interfaces serves two purposes: first, by extending the JpaRepository, we get a bunch of generic CRUD methods, like save, findAll, delete, and so on.
To Create Complex Queries, Why Specification?
Yes, complex queries can be build using the Criteria API. For any complex-enough API – searching/filtering your resources by very simple fields is simply not enough. A query language is more flexible and allows you to filter down to exactly the resources you need.
Hibernate specifics
Strategy Design Pattern and Lambda's
Read this wonderful post about different classifications of patterns!!!
The idea of the strategy pattern is to define a family of algorithms, encapsulate what varies into separate classes and make their objects interchangeable in the context. Varies here means: may change over time due to the evolving requirements.
Lambda expressions have changed the world in Java, and we can effectively use lambda expressions to avoid writing a lot of ceremonial code. As far as the strategy design pattern is concerned we don't have to create a hierarchy of classes. Instead, we can directly pass the strategy implementation of the interface as a lambda expression to the context.
Take one functional interface that fits your family of algorithms, declare them all statically in one place (single class).
All You Need To Know For Migrating To Java 11
We haven't fully immersed ourselves in Java 10 yet, and Java 11 is here. Java 11 is important for more than just a few reasons. Oracle has revamped its support model and come up with a release train that'll bring rapid updates, about every 6 months.
Negate a Predicate with Java 11
people.stream() .filter(Predicate.not(Person::isAdult)) .collect(Collectors.toList());
Mockito
- Any matchers and eq
- Baeldung argument matchers
- Mockito 2 examples
- Baeldung Mockito series
- Mocking Exception Throwing using Mockito
- Mock void methods with Mockito
- ArgumentCaptor
- verify Cookbook
Migrating from JUnit 4 to JUnit 5
Let's start with the previous version – JUnit 4 has some clear limitations:
- The entire framework was contained in a single jar library. The whole library needs to be imported even when only a particular feature is required. In JUnit 5, we get more granularity and can import only what is necessary
- One test runner can only execute tests in JUnit 4 at a time (e.g. SpringJUnit4ClassRunner or Parameterized ). JUnit 5 allows multiple runners to work simultaneously
- JUnit 4 never advanced beyond Java 7, missing out on a lot of features from Java 8. JUnit 5 makes good use of Java 8 features
- Migrating from a JUnit4-Based Runner
- junit 5 migration for Springboot applications
- Junit5 and @RunWith
- Guide to JUnit5
- how to integrate Mockito with the JUnit 5 extension model
- Unit testing with JUnit 5, Mockito, and Hamcrest
Java 8 Date – LocalDate, LocalDateTime, Instant
Java 8 Date Time API is one of the most sought after change for developers. Java has been missing a consistent approach for Date and Time from start and Java 8 Date Time API is a welcome addition to the core Java APIs.
Time Complexity of Java Collections
we'll talk about the performance of different collections from the Java Collection API. Usually, when we talk about time complexity, we refer to Big-O notation. Simply put, the notation describes how the time to perform the algorithm grows with the size of the input. This notation approximately describes how the time to do a given task grows with the size of the input. ... Roughly speaking, on one end we have O(1) which is “constant time” and on the opposite end we have O(xn) which is “exponential time”.
- Constant means that the time is always the same, it doesn't matter the length of the List
- Linear time means the longer the
ArrayList
is (more object it contains) the longer time the op will take, linear means that the more the List grows, the longer is the time, but in a linear way, so for example to perform a linear operation on a list that contains 20 elements it will take two times the time needed for a list with 10 elements.
- If you need fast access to elements using index, ArrayList should be choice.
- If you need fast access to elements using a key, use HashMap.
- If you need fast add and removal of elements, use LinkedList (but it has a very poor seeking performance).