Purpose: This section contains the practical code snippets most commonly requested during Java/Spring Boot interviews. Each example is intentionally small so it can be explained quickly on a whiteboard.
1. Main class – @SpringBootApplication
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2. Controller + Service + Repository structure
@RestController
@RequestMapping("/api/orders")
public class OrderController {
private final OrderService service;
public OrderController(OrderService service) {
this.service = service;
}
@GetMapping("/{id}")
public Order getOrder(@PathVariable Long id) {
return service.getOrder(id);
}
}
@Service
public class OrderService {
private final OrderRepository repository;
public OrderService(OrderRepository repository) {
this.repository = repository;
}
public Order getOrder(Long id) {
return repository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Order not found"));
}
}
@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
}
3. @Configuration + @Bean
@Configuration
public class AppConfig {
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
}
4. Constructor injection with multiple implementations
public interface PaymentService {
void pay();
}
@Service("cardPayment")
public class CardPaymentService implements PaymentService {
public void pay() {
System.out.println("Card payment");
}
}
@Service("upiPayment")
public class UpiPaymentService implements PaymentService {
public void pay() {
System.out.println("UPI payment");
}
}
@Service
public class CheckoutService {
private final PaymentService paymentService;
public CheckoutService(
@Qualifier("upiPayment") PaymentService paymentService) {
this.paymentService = paymentService;
}
}
5. REST CRUD API
@RestController
@RequestMapping("/api/products")
public class ProductController {
@GetMapping("/{id}")
public ResponseEntity<Product> get(@PathVariable Long id) {
return ResponseEntity.ok(service.get(id));
}
@PostMapping
public ResponseEntity<Product> create(
@Valid @RequestBody ProductRequest request) {
Product saved = service.create(request);
return ResponseEntity.status(HttpStatus.CREATED).body(saved);
}
@PutMapping("/{id}")
public ResponseEntity<Product> update(
@PathVariable Long id,
@Valid @RequestBody ProductRequest request) {
return ResponseEntity.ok(service.update(id, request));
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
service.delete(id);
return ResponseEntity.noContent().build();
}
}
6. DTO validation
public class UserRequest {
@NotBlank(message = "Name is required")
private String name;
@Email(message = "Invalid email")
@NotBlank
private String email;
@Min(value = 18, message = "Age must be at least 18")
private int age;
// getters and setters
}
7. Global exception handling
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ApiError> handleNotFound(
ResourceNotFoundException ex,
HttpServletRequest request) {
ApiError error = new ApiError(
Instant.now(),
404,
"RESOURCE_NOT_FOUND",
ex.getMessage(),
request.getRequestURI());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiError> handleValidation(
MethodArgumentNotValidException ex) {
String message = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(FieldError::getDefaultMessage)
.collect(Collectors.joining(", "));
return ResponseEntity.badRequest()
.body(new ApiError(Instant.now(), 400,
"VALIDATION_ERROR", message, null));
}
}
8. Immutable class
public final class Employee {
private final String id;
private final String name;
private final List<String> skills;
public Employee(String id, String name, List<String> skills) {
this.id = id;
this.name = name;
this.skills = List.copyOf(skills); // defensive copy
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public List<String> getSkills() {
return skills;
}
}
9. Safe mutable state – AtomicInteger
@Service
public class CounterService {
private final AtomicInteger counter = new AtomicInteger();
public int increment() {
return counter.incrementAndGet();
}
public int get() {
return counter.get();
}
}
10. Safe concurrent map
@Service
public class CacheService {
private final ConcurrentHashMap<Long, String> cache =
new ConcurrentHashMap<>();
public void put(Long id, String value) {
cache.put(id, value);
}
public String get(Long id) {
return cache.get(id);
}
}
11. @ConfigurationProperties
@ConfigurationProperties(prefix = "payment")
public class PaymentProperties {
private String url;
private Duration timeout;
private int retry;
// getters and setters
}
payment:
url: https://payment-service
timeout: 5s
retry: 3
12. Profiles
# application.yml
spring:
profiles:
active: dev
# application-dev.yml
server:
port: 8080
# application-prod.yml
server:
port: 8080
Production deployments can set SPRING_PROFILES_ACTIVE=prod externally instead of hard-coding it.
13. Separate Actuator / metrics port
server.port=8080
management.server.port=8081
management.endpoints.web.exposure.include=
health,info,metrics,prometheus
Application APIs can use port 8080 while management endpoints use port 8081.
14. CommandLineRunner
@Component
public class StartupRunner implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("Startup task executed");
}
}
15. ApplicationRunner
@Component
public class AppRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
System.out.println("Option names: " + args.getOptionNames());
}
}
16. @Transactional service method
@Service
public class TransferService {
@Transactional
public void transfer(Long from, Long to, BigDecimal amount) {
accountRepository.debit(from, amount);
accountRepository.credit(to, amount);
}
}
Interview point: Explain transaction boundaries, rollback behavior, proxy interception and the self-invocation limitation.
17. @Cacheable
@Service
public class ProductService {
@Cacheable(value = "products", key = "#id")
public Product getProduct(Long id) {
return repository.findById(id)
.orElseThrow();
}
@CacheEvict(value = "products", key = "#id")
public void delete(Long id) {
repository.deleteById(id);
}
}
18. CompletableFuture – parallel calls
CompletableFuture<User> user =
CompletableFuture.supplyAsync(() -> userClient.getUser(id));
CompletableFuture<Orders> orders =
CompletableFuture.supplyAsync(() -> orderClient.getOrders(id));
return user.thenCombine(orders,
(u, o) -> new UserDashboard(u, o));
19. CompletableFuture – exception handling
CompletableFuture.supplyAsync(() -> service.call())
.orTimeout(2, TimeUnit.SECONDS)
.exceptionally(ex -> {
log.error("Async call failed", ex);
return fallbackValue();
});
20. Virtual thread example (JDK 21+)
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
Future<String> future = executor.submit(() -> {
return callBlockingService();
});
System.out.println(future.get());
}
For Spring Boot, use the supported virtual-thread configuration for the Spring Boot/JDK version you deploy. Virtual threads improve concurrency for suitable blocking workloads; they do not make CPU-bound work inherently faster.
21. Spring Security – conceptual SecurityFilterChain
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http)
throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/actuator/health").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated());
return http.build();
}
22. Retry + timeout + circuit breaker – conceptual flow
Client
|
v
Order Service
|
+-- Timeout
|
+-- Retry (only transient failures)
|
+-- Circuit Breaker
|
v
Payment Service
|
X unavailable
|
v
Fallback / graceful response
Interview point: Never blindly retry every failure. Consider idempotency, retry count, backoff, jitter, timeouts and downstream capacity.
23. REST client – service-to-service call
@Service
public class PaymentClient {
private final RestClient restClient;
public PaymentClient(RestClient.Builder builder) {
this.restClient = builder
.baseUrl("http://payment-service")
.build();
}
public PaymentResponse getPayment(Long id) {
return restClient.get()
.uri("/api/payments/{id}", id)
.retrieve()
.body(PaymentResponse.class);
}
}
24. Kafka producer – conceptual example
@Service
public class OrderEventPublisher {
private final KafkaTemplate<String, OrderCreatedEvent> kafka;
public OrderEventPublisher(
KafkaTemplate<String, OrderCreatedEvent> kafka) {
this.kafka = kafka;
}
public void publish(OrderCreatedEvent event) {
kafka.send("order-created", event.orderId(), event);
}
}
25. Health endpoint – custom HealthIndicator
@Component
public class PaymentHealthIndicator implements HealthIndicator {
@Override
public Health health() {
boolean available = checkPaymentService();
if (available) {
return Health.up()
.withDetail("payment", "available")
.build();
}
return Health.down()
.withDetail("payment", "unavailable")
.build();
}
}
26. Custom Micrometer metric
@Service
public class OrderService {
private final Counter orderCounter;
public OrderService(MeterRegistry registry) {
this.orderCounter = Counter.builder("orders.created")
.description("Number of created orders")
.register(registry);
}
public void createOrder() {
// business logic
orderCounter.increment();
}
}
27. Java 8 Stream example
List<String> names =
Arrays.asList("Ravi", "John", "Robert", "Sam");
List<String> result = names.stream()
.filter(name -> name.length() > 4)
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());
28. Optional example
public Product findProduct(Long id) {
return repository.findById(id)
.orElseThrow(() ->
new ResourceNotFoundException(
"Product not found: " + id));
}
29. Java 8 functional interfaces
Predicate<Integer> positive =
n -> n > 0;
Function<String, Integer> length =
String::length;
Consumer<String> printer =
System.out::println;
Supplier<UUID> idSupplier =
UUID::randomUUID;
30. Idempotency – simple REST pattern
@PostMapping("/payments")
public ResponseEntity<PaymentResponse> create(
@RequestHeader("Idempotency-Key") String key,
@RequestBody PaymentRequest request) {
// 1. Look up key in durable storage
// 2. If already processed, return stored response
// 3. Otherwise process once
// 4. Store result against key
return ResponseEntity.status(HttpStatus.CREATED)
.body(service.processOnce(key, request));
}