Boost Your Spring Boot 3 Projects with 20 Powerful Tips & Real-World Examples

This article presents a curated collection of 20 practical Spring Boot 3 techniques—from configuration and custom banners to DevTools, Actuator, validation, AOP logging, caching, async tasks, dynamic data sources, Jackson customization, scheduling, Testcontainers testing, and retry mechanisms—helping developers dramatically improve productivity and build robust backend applications.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Boost Your Spring Boot 3 Projects with 20 Powerful Tips & Real-World Examples

Introduction

Spring Boot 3.4.2 offers a collection of 20 practical techniques to improve development efficiency, covering configuration management, custom banners, disabling unnecessary auto‑configuration, startup runners, builder API, profile‑based settings, conditional beans, DevTools, Actuator monitoring, validation, global exception handling, AOP logging, embedded servlet customization, caching, asynchronous tasks, externalized configuration, dynamic data sources, Jackson customization, scheduled jobs, Testcontainers testing, and retry mechanisms.

Key Techniques

1. @ConfigurationProperties

Map related properties to a POJO for cleaner code.

@Component
@ConfigurationProperties(prefix = "pack.app")
public class RemoteProperties {
    private String host;
    private int port;
    private String schema;
    // getters, setters
}

Corresponding YAML:

pack:
  app:
    schema: ftp
    host: localhost
    port: 22

2. Custom Banner

Place a banner.txt file under src/main/resources to display a custom startup banner.

Custom banner example
Custom banner example

3. Disable Unwanted Auto‑Configuration

@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class App { … }

Or in application.yml:

spring:
  autoconfigure:
    exclude:
      - org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

4. CommandLineRunner / ApplicationRunner

Execute initialization logic after the application starts.

@Component
public class LoadCacheRunner implements CommandLineRunner {
    @Override
    public void run(String... args) { /* … */ }
}

5. SpringApplicationBuilder

new SpringApplicationBuilder(App.class)
    .profiles("dev")
    .properties("server.port=6666")
    .run(args);

6. @Profile

@Configuration
public class DataSourceConfig {
    @Bean @Profile("dev")
    public DataSource devDataSource() { … }

    @Bean @Profile("prod")
    public DataSource prodDataSource() { … }
}

7. @ConditionalOnProperty

@Configuration
public class PackCacheConfig {
    @Bean
    @ConditionalOnProperty(name = "pack.cache.enabled", havingValue = "true")
    public PackCache cache() { return new PackCache(); }
}

8. DevTools

Add the optional dependency spring-boot-devtools to enable hot reload.

9. Actuator

Include spring-boot-starter-actuator to expose health and metrics endpoints.

Actuator endpoints
Actuator endpoints

10. Validation

public class UserDTO {
    @NotBlank(message = "用户名不能为空")
    private String username;
    @Pattern(regexp = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$", message = "邮箱格式不正确")
    private String email;
}

11. Global Exception Handling

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleException(Exception ex) { /* … */ }
}

12. AOP Logging

@Aspect @Component
public class LoggingAndPerformanceAspect {
    @Around("@annotation(requestMapping)")
    public Object logAndMeasurePerformance(ProceedingJoinPoint jp, RequestMapping rm) throws Throwable { /* … */ }
}

13. Embedded Servlet Customization

server:
  tomcat:
    max-threads: 200
    max-connections: 1000

14. Caching

@Configuration @EnableCaching
public class AppConfig { }

@Service
public class UserService {
    @Cacheable(value = "users", key = "#id")
    public User getUserById(Long id) { /* … */ }
}

15. Asynchronous Tasks

@Configuration @EnableAsync
public class AppConfig { }

@Service
public class TaskService {
    @Async
    public void processLongTask() { /* … */ }
}

16. Externalized Configuration

Place application.yml in a config directory or specify --spring.config.location at runtime.

17. Dynamic Data Source

@Configuration
public class DataSourceConfig {
    @Bean @ConfigurationProperties(prefix = "spring.datasource.first")
    public DataSource firstDataSource() { return DataSourceBuilder.create().build(); }
    @Bean @ConfigurationProperties(prefix = "spring.datasource.second")
    public DataSource secondDataSource() { return DataSourceBuilder.create().build(); }
}

18. Jackson Customization

@Configuration
public class JacksonConfig {
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customizer() {
        return builder -> {
            JavaTimeModule module = new JavaTimeModule();
            module.addSerializer(LocalDateTime.class,
                new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                   .modules(module);
        };
    }
}

19. Scheduling

@Component
public class ScheduledTask {
    @Scheduled(cron = "0 0 1 * * ?")
    public void cleanExpiredData() { /* … */ }
}

20. Testcontainers

@Testcontainers @SpringBootTest
public class DatabaseTest {
    @Container
    static MySQLContainer<?> mysql = new MySQLContainer<>("mysql:8.0.26")
        .withDatabaseName("testdb")
        .withUsername("root")
        .withPassword("root");
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Test
    void testDatabaseInsert() { /* … */ }
}

21. Retry

@Configuration @EnableRetry
public class AppConfig { }

@Service
public class RemoteService {
    @Retry(maxAttempts = 3, backoff = @Backoff(delay = 1000, multiplier = 2))
    public ApiResponse callRemoteService(String request) { /* … */ }

    @Recover
    public ApiResponse recoverRemoteServiceCall(Exception e, String request) {
        return new ApiResponse("调用失败");
    }
}

These examples provide a quick reference for building robust, high‑performance Spring Boot applications.

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.

ConfigurationDevToolsbackend-developmentActuatorspring-boot
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.