Unlock 10 Hidden Spring Boot Tricks to Supercharge Your Apps

This article introduces a free Spring Boot 3 ebook collection of 164 practical cases and shares ten powerful techniques—including custom @Conditional logic, lazy initialization, structured configuration binding, custom starters, Testcontainers testing, event‑driven programming, hidden Actuator endpoints, fine‑grained startup control, Tomcat performance tuning, and monitoring—to help developers build leaner, faster, and more maintainable backend services.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Unlock 10 Hidden Spring Boot Tricks to Supercharge Your Apps

Spring Boot 3 Practical Case Collection

The ebook, now updated to 164 examples, offers a permanent free subscription for continuous updates. Readers can download the PDF by subscribing through the provided link.

1. Introduction

Many developers find Spring Boot projects becoming bloated or repeatedly solving problems that the framework could handle automatically. The author shares ten lesser‑known but highly useful tricks gathered from real‑world development experience.

2. Embedded Tomcat Performance Tuning

Tomcat’s default configuration is not optimized for high‑load scenarios, leading to latency, thread starvation, excessive GC, and connection timeouts. The article summarizes seven tuning secrets:

Increase thread pool size (min‑spare, max)

Adjust connection timeout

Enable keep‑alive and configure keep‑alive timeout and max requests

Increase accept‑count (queue size)

Enable response compression for JSON, XML, HTML, etc.

Select the appropriate connector (NIO, NIO2, APR) and configure APR if needed

Monitor and adjust using Micrometer + Actuator metrics

Example: Thread Pool Configuration

server:
  tomcat:
    threads:
      min-spare: 20
      max: 200

Example: Connection Timeout

server:
  tomcat:
    connection-timeout: 20000

Example: Keep‑Alive Settings

server:
  tomcat:
    keep-alive-timeout: 15000
    max-keep-alive-requests: 100

Example: Compression

server:
  compression:
    enabled: true
    mime-types: application/json,application/xml,text/html,text/plain
    min-response-size: 1024

3. Practical Development Techniques

3.1 Custom Conditional Control (@Conditional)

Beyond @ConditionalOnProperty, developers can define their own Condition to load beans only when certain resources (e.g., Redis) are available.

public class OnRedisAvailableCondition implements Condition {
  @Override
  public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    try (Socket socket = new Socket("localhost", 6379)) {
      return true;
    } catch (Exception e) {
      return false;
    }
  }
}

@Configuration
public class RedisConfig {
  @Bean
  @Conditional(OnRedisAvailableCondition.class)
  public RedisClient redisClient() {
    return new RedisClient("localhost", 6379);
  }
}

More examples are linked in the original article.

3.2 Lazy Initialization

Enable bean lazy loading to reduce startup time.

spring:
  main:
    lazy-initialization: true

3.3 Structured Configuration Binding

Use @ConfigurationProperties to bind nested YAML structures directly to POJOs.

pack:
  app:
    servers:
      - url: https://order.pack.com
        timeout: 5000
      - url: https://product.pack.com
        timeout: 3000
    features:
      auth: true
      cache: false

@ConfigurationProperties(prefix = "pack.app")
public class AppProperties {
  private List<ServerConfig> servers;
  private Map<String, Boolean> features;
  // getters and setters
  public static class ServerConfig {
    private String url;
    private int timeout;
  }
}

3.4 Custom Starter Development

Create an auto‑configuration class, register it in META‑INF, and publish the starter as a JAR to provide reusable beans such as logging, monitoring, or security.

@Configuration
public class LoggingAutoConfiguration {
  @Bean
  public LoggerService loggerService() {
    return new LoggerService();
  }
}

For Spring Boot 2.x, add the class to spring.factories; for 3.x, use AutoConfiguration.imports.

3.5 Testcontainers for Real‑Service Testing

Replace in‑memory databases with Docker‑based containers for integration tests.

@SpringBootTest
@Testcontainers
public class UserRepositoryTest {
  @Container
  static MySQLContainer<?> mysql = new MySQLContainer<>("mysql:latest");

  @DynamicPropertySource
  static void registerProps(DynamicPropertyRegistry registry) {
    registry.add("spring.datasource.url", mysql::getJdbcUrl);
    registry.add("spring.datasource.username", mysql::getUsername);
    registry.add("spring.datasource.password", mysql::getPassword);
  }

  @Resource
  private UserRepository repository;

  @Test
  void shouldSaveUser() {
    repository.save(new User("Alice"));
    assertThat(repository.findAll()).hasSize(1);
  }
}

3.6 Event‑Driven Programming

Use @EventListener to decouple components via Spring events.

@Component
public class OrderService {
  private final ApplicationEventPublisher publisher;
  public void placeOrder(Order order) {
    publisher.publishEvent(new OrderPlacedEvent(order));
  }
}

@Component
public class NotificationHandler {
  @EventListener
  public void handleOrderPlaced(OrderPlacedEvent event) {
    System.out.println("Send email for order: " + event.getOrder().getId());
  }
}

3.7 Hidden Actuator Debug Endpoints

Beyond /actuator/health, enable /actuator/conditions, /actuator/configprops, /actuator/mappings, etc., to diagnose bean creation and configuration.

management:
  endpoints:
    web:
      exposure:
        include: health,info,conditions,configprops,mappings

3.8 Fine‑Grained Startup Control

Implement ApplicationRunner to run logic after the full context is ready, avoiding pitfalls of @PostConstruct.

@Component
public class PackRunner implements ApplicationRunner {
  @Override
  public void run(ApplicationArguments args) {
    // custom startup logic here
  }
}

3.9 Configuration Groups

Activate multiple profiles with a single group definition (e.g., dev includes h2 and debug).

spring:
  profiles:
    active:
      - dev
    group:
      dev: [h2,debug]
      prod: [mysql,logging]

4. Monitoring and Metrics

Add spring-boot-starter-actuator and expose metrics for Tomcat threads, request rates, and error counts. Use Prometheus + Grafana for visualization.

management:
  endpoints:
    web:
      exposure:
        include: metrics,health

5. Conclusion

The article provides a comprehensive set of Spring Boot tricks, from low‑level Tomcat tuning to high‑level architectural patterns, all bundled in a freely downloadable PDF ebook.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Spring BootTestcontainersCustom ConditionsStarter Development
Spring Full-Stack Practical Cases
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.