Spring Boot In Action [VERIFIED]
@WebMvcTest(UserController.class) class UserControllerMvcTest { }
@Scheduled(fixedDelay = 5000) public void fixedDelayTask() { // Runs 5 seconds after previous execution } spring boot in action
This comprehensive guide covers the essential features of Spring Boot in action for building production-ready applications. @WebMvcTest(UserController
public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findByEmail(String email); @Query("SELECT u FROM User u WHERE u.email LIKE %:domain") List<User> findByEmailDomain(@Param("domain") String domain); } @Repository public class JdbcUserRepository { private final JdbcTemplate jdbcTemplate; public List<User> findAll() { return jdbcTemplate.query("SELECT * FROM users", (rs, rowNum) -> new User(rs.getLong("id"), rs.getString("email"))); } } MongoDB, Redis, etc. // MongoDB @Document(collection = "products") public class Product { } // Redis @RedisHash("sessions") public class UserSession { } 4. Web Development REST Controllers @RestController @RequestMapping("/api/users") public class UserController { @GetMapping public ResponseEntity<List<User>> getAll() { return ResponseEntity.ok(users); } getAll() { return ResponseEntity.ok(users)
@PostMapping @ResponseStatus(HttpStatus.CREATED) public User create(@Valid @RequestBody User user) { return userService.save(user); }
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoggingInterceptor()) .addPathPatterns("/api/**"); } } @RestController public class ReactiveUserController { @GetMapping("/flux/users") public Flux<User> getAllReactive() { return userReactiveRepository.findAll() .delayElements(Duration.ofSeconds(1)); }
@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 )); }