Master Spring Boot 3: 8 Real-World Cases to Boost Your Backend Skills
This article presents eight practical Spring Boot 3 examples—including Resilience4j protection, custom Actuator endpoints, distributed transactions, caching, asynchronous programming, API gateway, OAuth2/JWT security, and scheduled tasks—each with code snippets and configuration guidance to help developers build robust backend services.
Spring Boot 3 practical case collection updated to 113 examples, continuously refreshed for developers.
1. Protect Services with Resilience4j
In microservices, handle transient failures gracefully. Resilience4j integrates with Spring Boot offering Circuit Breaker, Retry, and Rate Limiter patterns.
Dependency
<code><dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot3</artifactId>
<version>2.2.0</version>
</dependency></code>Usage Example
<code>@CircuitBreaker(name = "userList", fallbackMethod = "findAllFallback")
public List<User> findAll() {
// ...
}
public List<User> findAllFallback(Throwable ex) {
System.err.printf("Exception: %s%n", ex.getMessage());
return List.of();
}</code>Configuration (application.yml):
<code>resilience4j:
circuitbreaker:
configs:
userCfg:
minimum-number-of-calls: 2
wait-duration-in-open-state: 10s
instances:
userList:
base-config: userCfg</code>2. Custom Actuator Endpoint
Spring Boot Actuator exposes metrics and health checks; you can add custom endpoints for application‑specific monitoring.
Dependency
<code><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency></code>Custom Health Indicator Example
<code>@Component
public class PackHealthIndicator implements HealthIndicator {
public Health health() {
int errorCode = check();
if (errorCode != 0) {
return Health.down().withDetail("Error Code", errorCode).build();
}
return Health.up().build();
}
private int check() {
return new Random().nextInt(2);
}
}</code>3. Distributed Transactions in Microservices
Managing transactions across services is challenging; use the Saga pattern or JTA for eventual consistency and atomicity.
Saga with Kafka Example
<code>@Service
public class OrderService {
private final KafkaTemplate<String, OrderEvent> kafkaTemplate;
public void createOrder(String orderId) {
OrderEvent orderEvent = new OrderEvent(orderId, "CREATE");
kafkaTemplate.send("order-events", orderEvent);
}
}
@KafkaListener(topics = "order-events")
public void processOrder(OrderEvent event) {
if ("ORDER_CREATED".equals(event.getStatus())) {
// ...
}
}</code>For more details see Spring JPA JTA documentation.
4. Cache to Improve Performance
Enable caching to reduce database access.
Enable Cache
<code>@Configuration
@EnableCaching
public class App {}</code>Cacheable Method
<code>@Cacheable(value = "users", key = "#userId")
public User getUserById(String userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new UserNotFoundException(userId));
}</code>5. Asynchronous Programming
Use @Async for simple asynchronous execution.
Enable Async
<code>@EnableAsync
@Configuration
public class App {}</code>Async Service Example
<code>@Service
public class EmailService {
@Async
public void sendEmail(String email, String message) {
// ...
}
}</code>6. API Gateway
Spring Cloud Gateway provides a reactive API gateway with better performance than Netflix Zuul.
Key Features
Routing and filtering
Integration with Resilience4j for circuit breaking
WebSocket support and load balancing
Programmatic Route Definition
<code>@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("user_route", r -> r.path("/users/**")
.uri("http://user-service"))
.build();
}</code>7. Secure Application with OAuth2 or JWT
OAuth2 and JWT are commonly used to protect API endpoints.
Custom Security Filter Example
<code>public class AuthenticationFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
try {
Authentication authentication = AuthenticationService.getAuthentication((HttpServletRequest) request);
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (Exception e) {
return;
}
filterChain.doFilter(request, response);
}
}</code>Add Filter to Security Chain
<code>@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(registry -> registry.requestMatchers("/**").authenticated())
.httpBasic(Customizer.withDefaults())
.sessionManagement(h -> h.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(new AuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}</code>8. Scheduled Tasks
Enable scheduling to run periodic jobs.
Enable Scheduling
<code>@Configuration
@EnableScheduling
public class App {}</code>Scheduled Method Example
<code>@Scheduled(cron = "*/10 * * * * *")
public void task() {
// ...
}</code>These eight examples provide a solid foundation for building robust, performant, and secure Spring Boot 3 applications.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.