@Scheduled(initialDelay = 10000, fixedRate = 30000) public void fixedRateTask() { } } @Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(100); executor.initialize(); return executor; } }
This comprehensive guide covers the essential features of Spring Boot in action for building production-ready applications. spring boot in action
@Scheduled(cron = "0 0 * * * *") public void hourlyTask() { // Runs every hour } @Scheduled(initialDelay = 10000
@GetMapping(value = "/stream/users", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<User> streamUsers() { return Flux.interval(Duration.ofSeconds(2)) .map(tick -> new User()); } } Basic Security Configuration @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http .authorizeHttpRequests(auth -> auth .requestMatchers("/public/**", "/api/auth/**").permitAll() .requestMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() ) .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .build(); } produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<
@Component @RabbitListener(queues = "order.queue") public class OrderListener { @RabbitHandler public void handleOrder(Order order) { System.out.println("Received order: " + order.getId()); } } File Upload @PostMapping("/upload") public ResponseEntity<String> handleUpload(@RequestParam("file") MultipartFile file) throws IOException { Path path = Paths.get("uploads/" + file.getOriginalFilename()); Files.write(path, file.getBytes()); return ResponseEntity.ok("File uploaded successfully"); } // Async file processing @Async public CompletableFuture<String> processFile(MultipartFile file) { // Process large files asynchronously } 14. Error Handling Global Exception Handler @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public Map<String, String> handleValidation(MethodArgumentNotValidException ex) { return ex.getBindingResult().getFieldErrors().stream() .collect(Collectors.toMap( FieldError::getField, FieldError::getDefaultMessage )); }