Spring boot Q & A
What is Spring Boot Actuator?
Answer: The Actuator provides production-ready endpoints to monitor and manage the application. Examples include /actuator/health, /actuator/metrics, and /actuator/info. These endpoints help with diagnostics and integration with monitoring tools.
What are Spring Profiles and how do you use them?
Answer: Profiles allow environment-specific configurations. You can define application-dev.yml, application-prod.yml, etc., and activate them using spring.profiles.active=dev. Beans can be annotated with @Profile("dev") to load conditionally.
How do you implement caching in Spring Boot?
Answer: Enable caching with @EnableCaching and use @Cacheable, @CachePut, and @CacheEvict annotations. You can configure cache providers like EhCache, Redis, or Caffeine in your application.
How do you test a Spring Boot application?
Answer: Use JUnit and Mockito for unit testing. For integration tests, use @SpringBootTest. You can mock beans using @MockBean and test REST endpoints with TestRestTemplate or WebTestClient.
Describe a challenging bug you faced and how you resolved it.
Answer: In one project, I faced a circular dependency issue between service beans. The application failed to start. I resolved it by refactoring the code to decouple responsibilities and introduced interfaces to break the cycle.
How do you ensure code quality in your Spring Boot projects?
Answer: I follow SOLID principles, write unit and integration tests, use tools like SonarQube for static analysis, and participate in code reviews. I also use meaningful logging and maintain proper documentation.
How do you optimize performance in Spring Boot?
Answer: I use caching, connection pooling, lazy loading, and asynchronous processing (@Async ). I also profile the application using Actuator metrics and external tools like Prometheus and Grafana.
What is Spring Boot, and how is it different from Spring Framework?
Answer: Spring Boot is an extension of the Spring Framework that simplifies application development by offering auto-configuration, embedded servers (like Tomcat), and production-ready features. Unlike traditional Spring, it eliminates the need for extensive XML configuration and manual setup.
How do you handle database migrations in Spring Boot?
Answer: Using tools like Flyway or Liquibase:
i) Define migration scripts in db/migration folder
ii) Spring Boot auto-detects and runs them on startup
iii) Versioning ensures consistency across environments
This approach supports CI/CD pipelines and avoids manual schema changes.
What is the difference between @Component, @Repository, @Service, and @Controller?
Answer:
All are specializations of @Component, but they serve semantic purposes:
@Repository: DAO layer, enables exception translation
@Service: Business logic layer
@Controller: Web layer, handles HTTP requests
@Component: Generic bean
How do you externalize configuration in Spring Boot for multiple environments?
Answer:
.Use application-(profile).yml or properties
.Activate profiles via spring.profiles.active
.Use environment variables or command-line arguments
.For secrets, integrate with Vault or AWS Parameter Store
Spring Security:
How does Spring Security handle authentication and authorization?
→ Authentication: verifying user identity (username/password, tokens).
→ Authorization: granting access based on roles/permissions.
→ Configured via
SecurityFilterChainorWebSecurityConfigurerAdapter(deprecated).→ Supports multiple mechanisms: form login, JWT, OAuth2.
How would you implement JWT authentication in Spring Security?
→ Steps:
User logs in → server generates JWT with claims.
Client stores JWT (usually in localStorage).
For each request, client sends JWT in
Authorization: Bearer <token>.Spring Security filters validate JWT signature and expiry.
If valid, user is authenticated; else rejected.
What is the difference between Authentication and Authorization in Spring Security?
Authentication: Verifies who the user is (identity).
Authorization: Decides what the authenticated user can access (permissions/roles).
Example: Logging in with username/password is authentication; accessing
/adminonly if you haveROLE_ADMINis authorization.
How does Spring Security implement filters in the security chain?
→ Spring Security uses a filter chain (
DelegatingFilterProxy) that intercepts requests.→ Filters like
UsernamePasswordAuthenticationFilter,BasicAuthenticationFilter, and custom JWT filters run in sequence.→ Each filter decides whether to authenticate, authorize, or pass the request further.
What is CSRF protection in Spring Security and why is it important?
→ CSRF (Cross-Site Request Forgery) occurs when malicious sites trick users into performing unintended actions.
→ Spring Security enables CSRF protection by default for state-changing requests (POST, PUT, DELETE).
→ It generates a CSRF token stored in the session and requires it in every request to validate authenticity.
How do you secure REST APIs with Spring Security?
→ Use JWT tokens or OAuth2 instead of session-based authentication.
→ Configure stateless security (
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)).→ Add a custom filter to validate tokens before requests reach controllers.
→ Example: Protect endpoints with
@PreAuthorize("hasRole('ADMIN')").What is the difference between OAuth2 and JWT in Spring Security?
JWT: Self-contained token with claims, signed by server. No need to call auth server repeatedly.
OAuth2: Delegated authorization framework, often used with external providers (Google, GitHub).
JWT is often used within microservices; OAuth2 is used for third-party integrations.
How do you implement Role-Based Access Control (RBAC) in Spring Security?
→ Define roles (
ROLE_USER,ROLE_ADMIN) in database or config.→ Map roles to authorities.
→ Use annotations:
java
@PreAuthorize("hasRole('ADMIN')") public void deleteUser(Long id) { ... }→ Or configure in
HttpSecurity:java
http.authorizeHttpRequests() .requestMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated();How does Spring Security integrate with JWT expiration and refresh tokens?
→ JWTs usually have short lifespans for security.
→ A refresh token (longer lifespan) is issued alongside the access token.
→ When access token expires, client uses refresh token to request a new one.
→ Spring Security can handle this via custom endpoints and filters.
What is method-level security in Spring Security?
→ Enables fine-grained access control at the method level.
→ Annotations:
@PreAuthorize("hasRole('ADMIN')")@PostAuthorize("returnObject.owner ==authentication.name")
→ Must enable with @EnableGlobalMethodSecurity(prePostEnabled = true) (Spring Boot 2) or @EnableMethodSecurity (Spring Boot 3).
How do you secure microservices communication with Spring Security?
→ Use service-to-service authentication with JWT or OAuth2.
→ Each service validates incoming tokens.
→ Optionally, use API Gateway for centralized authentication.
→ Mutual TLS (mTLS) can be used for stronger security between services.
What is the difference between Basic Authentication and Bearer Token Authentication in Spring Security?
→ Basic Auth: Username/password encoded in Base64, sent with every request. Simple but insecure for production.
→ Bearer Token (JWT/OAuth2): Token issued after authentication, sent in
Authorization: Bearer <token>. More secure, stateless, and scalable.