ESPORTS

Spring Boot In Action !!install!! [ Instant · 2027 ]

@Service public class EmailService { @Async public CompletableFuture<Void> sendEmail(String to, String content) { // Simulate email sending return CompletableFuture.completedFuture(null); } } RabbitMQ @Configuration public class RabbitConfig { @Bean public Queue queue() { return new Queue("order.queue", false); } @Bean public TopicExchange exchange() { return new TopicExchange("order.exchange"); } }

@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(); }

@Test void shouldCreateUser() throws Exception { User user = new User("test@example.com"); given(userService.save(any())).willReturn(user); mockMvc.perform(post("/api/users") .contentType(MediaType.APPLICATION_JSON) .content("{\"email\":\"test@example.com\"}")) .andExpect(status().isCreated()) .andExpect(jsonPath("$.email").value("test@example.com")); } spring boot in action

@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 )); }

@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)); } getAll() { return ResponseEntity.ok(users)

// Activate profile // --spring.profiles.active=dev,swagger Logback Configuration <!-- logback-spring.xml --> <configuration> <springProfile name="dev"> <root level="DEBUG"/> </springProfile> <springProfile name="prod"> <root level="INFO"/> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logs/app.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>logs/app-%d{yyyy-MM-dd}.log</fileNamePattern> </rollingPolicy> </appender> </springProfile> </configuration> Structured Logging @Slf4j @Service public class OrderService { public void processOrder(Order order) { log.info("Processing order: {}", order.getId()); MDC.put("orderId", order.getId().toString()); try { // business logic } finally { MDC.clear(); } } } 10. Caching Enable Caching @Configuration @EnableCaching public class CacheConfig { @Bean public CacheManager cacheManager() { return new ConcurrentMapCacheManager("users", "products"); } }

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); } } } @GetMapping(value = "/stream/users"

public void publish(Order order) { rabbitTemplate.convertAndSend("order.exchange", "order.created", order); } }