Part 3: Spring Boot & Microservices
Section 1: Spring Boot Fundamentals
Q1: What is Spring Boot and why use it? Answer: Spring Boot simplifies Spring application setup by providing auto-configuration, embedded servers, opinionated defaults, and production-ready features. It reduces boilerplate and accelerates microservice development.
Q2: Explain auto-configuration in Spring Boot.
- Spring Boot detects classes on the classpath and configures beans automatically.
- Example:
spring-boot-starter-webautomatically sets upDispatcherServlet,Jackson, and embedded Tomcat. - Pitfall: Conflicting dependencies can lead to unexpected bean creation.
Q3: What are Spring Boot Starters?
- Predefined dependencies that simplify setup.
- Examples:
spring-boot-starter-web,spring-boot-starter-data-jpa,spring-boot-starter-security.
Q4: Profiles in Spring Boot
- Support environment-specific configuration (
application-dev.yml,application-prod.yml). - Activate via
spring.profiles.active=dev.
Q5: Difference between @SpringBootApplication and @EnableAutoConfiguration
@SpringBootApplicationcombines:@Configuration,@EnableAutoConfiguration,@ComponentScan.
Section 2: Spring Boot Actuator & Monitoring
Q6: What is Spring Boot Actuator?
- Provides production-ready endpoints to monitor and manage applications.
- Common endpoints:
/health,/metrics,/env,/loggers.
Q7: How to customize actuator endpoints?
management:
endpoints:
web:
exposure:
include: health, metrics, beans
Q8: Integrating with Prometheus & Grafana
- Expose
/actuator/prometheusand configure Prometheus to scrape metrics. - Pitfall: Avoid exposing sensitive endpoints in production.
Section 3: Spring Boot Testing
Q9: Types of Spring Boot tests
- Unit Tests: Test classes in isolation using JUnit + Mockito.
- Integration Tests:
@SpringBootTestloads context for real interactions. - Web Layer Tests:
@WebMvcTestfor controller testing.
Q10: Example – Unit Test with MockBean
@SpringBootTest
class OrderServiceTest {
@MockBean
PaymentService paymentService;
@Autowired
OrderService orderService;
@Test
void processOrder() {
Mockito.when(paymentService.pay()).thenReturn(true);
assertTrue(orderService.processOrder());
}
}
Q11: Test tips for interviews
- Always isolate external dependencies.
- Use
@DataJpaTestfor repository testing. - Cover both positive and negative scenarios.
Section 4: REST API Design & Best Practices
Q12: Key principles
- Use proper HTTP verbs (
GET,POST,PUT,DELETE). - Resource-based URIs:
/users/{id}/orders. - Versioning:
/api/v1/users. - Consistent error handling with
@ControllerAdvice.
Q13: Pagination & Sorting
Page<User> findAll(Pageable pageable);
Q14: HATEOAS (optional)
- Add hypermedia links to REST responses to guide clients.
Q15: Security considerations
- Validate input, use DTOs instead of entities, encode passwords, avoid exposing sensitive fields.
Section 5: Spring Boot Microservices
Q16: What is a microservice?
- Small, independently deployable service, focused on a single business capability.
- Benefits: Scalability, decoupling, maintainability.
Q17: Key Spring Cloud tools
- Service Discovery: Eureka
- Configuration: Spring Cloud Config
- API Gateway: Spring Cloud Gateway
- Circuit Breaker: Resilience4J
Q18: Example – Service Discovery with Eureka
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication { }
- Microservice registers itself with Eureka using
@EnableEurekaClient.
Q19: Inter-service communication
- REST (RestTemplate, WebClient)
- Feign Client: Declarative REST
@FeignClient(name="payment-service")
public interface PaymentClient {
@GetMapping("/pay")
boolean pay();
}
Q20: Circuit breaker example (Resilience4J)
@CircuitBreaker(name="paymentService", fallbackMethod="fallbackPay")
public boolean pay() { ... }
public boolean fallbackPay(Throwable t) { return false; }
Section 6: Event-Driven Microservices
Q21: Why event-driven?
- Decouples services, improves scalability, ensures eventual consistency.
Q22: Spring + Kafka example
// Producer
@Autowired KafkaTemplate<String, Order> kafkaTemplate;
kafkaTemplate.send("orders", order);
// Consumer
@KafkaListener(topics="orders")
public void consume(Order order) { process(order); }
Q23: Async processing
- Use
@Asyncwith ThreadPoolTaskExecutor for non-blocking execution. - Pitfall: Thread pools must be tuned for load; unbounded threads can crash services.
Section 7: Security in Microservices
Q24: JWT Authentication
- Stateless, signed token containing user info and roles.
- Example flow: Login → generate JWT → client sends in
Authorization: Bearerheader → validate JWT in filter.
Q25: OAuth2 & OpenID Connect
- Used for SSO and token-based authentication.
- Pitfall: Never trust client-side tokens without validation.
Q26: Securing endpoints
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.oauth2ResourceServer().jwt();
Section 8: Production & Performance Best Practices
- Keep services stateless.
- Externalize configuration using Spring Cloud Config.
- Enable logging and monitoring (Actuator + Prometheus).
- Tune JVM and thread pools for high throughput.
- Use DTOs, avoid lazy-loading pitfalls across microservice boundaries.
- Apply caching (Redis, Caffeine) for frequently accessed data.
- Implement retries, rate-limiting, and fallback strategies for resilience.