Spring Boot Interview Questions and Answers (2026)
Preparing for a Java developer interview? This guide covers 130+ Spring Boot interview questions with detailed answers — from beginner to advanced level — to help you crack interviews at product companies, service MNCs, and BFSI firms.
Whether you're a fresher applying for your first Java role or an experienced developer targeting senior positions, these questions cover everything interviewers actually ask: auto-configuration, Spring MVC, REST APIs, JPA and Hibernate, Spring Security with JWT, microservices, Spring Boot Actuator, Docker deployment, and more.
Topics covered in this guide:
- Spring Boot core concepts — what it is, how auto-configuration works,
@SpringBootApplication - Configuration & profiles —
application.properties, YAML, environment-specific configs - Dependency injection —
@Autowired,@Bean, constructor vs setter injection, IoC container - Web layer & REST —
@RestController, request mapping, validation, exception handling - Spring Data JPA — repositories,
@Transactional, JPQL, pagination - Spring Security — JWT authentication, BCrypt, OAuth2, method-level security
- Actuator & monitoring — health checks, metrics, custom endpoints
- Deployment — embedded Tomcat, WAR packaging, SSL, Docker, Spring Cloud
- Advanced topics — AOP, Spring Cloud, ApplicationRunner, YAML vs properties
Who this is for: Java freshers (0–2 years), mid-level Java developers (2–5 years), and senior engineers preparing for full-stack or backend-focused rounds at companies like TCS, Infosys, Wipro, Cognizant, Goldman Sachs, JP Morgan, Accenture, Capgemini, and product startups.
1. Spring Boot Core Concepts
Q1. What is Spring Boot?
Spring Boot is an open-source Java-based framework built on top of the Spring Framework. It simplifies the development of stand-alone, production-grade Spring applications by providing auto-configuration, embedded servers, and opinionated defaults — so developers can start building without boilerplate setup.
Key highlights:
- No need for XML configuration
- Embedded Tomcat/Jetty/Undertow server included
- Auto-configures Spring and third-party libraries
- Production-ready features like health checks and metrics via Actuator
Q2. What are the advantages of Spring Boot?
- Auto-Configuration: Automatically configures Spring application based on dependencies present in the classpath
- Standalone: Creates jar files with embedded servers — no need to deploy WAR files
- Opinionated Defaults: Provides sensible defaults to reduce boilerplate
- Spring Boot Starters: Pre-built dependency descriptors for common use cases
- Production Ready: Built-in Actuator for health checks, metrics, and monitoring
- Easy Testing: Spring Boot Test module simplifies unit and integration testing
- Microservices Ready: Works seamlessly with Spring Cloud for distributed systems
- Reduced Development Time: Less configuration means faster prototyping
Q3. What is the difference between Spring and Spring Boot?
| Feature | Spring Framework | Spring Boot |
|---|---|---|
| Configuration | Manual XML or Java config | Auto-configuration |
| Server | External server required | Embedded server included |
| Dependency Management | Manual version management | Managed via parent POM |
| Boilerplate | High | Minimal |
| Setup Time | Longer | Minutes |
| Deployment | WAR file to external server | Standalone JAR |
Spring Boot is built on top of Spring — it does not replace Spring. It just makes Spring easier to use.
Q4. What are the essential components of Spring Boot?
- Spring Boot Starters — Dependency descriptors that bundle related dependencies (e.g.,
spring-boot-starter-web) - Spring Boot Auto-Configuration — Automatically configures beans based on classpath
- Spring Boot CLI — Command-line tool to run Groovy scripts
- Spring Boot Actuator — Production-ready monitoring and management endpoints
- Spring Boot DevTools — Developer tools for hot reload and improved development experience
Q5. What is Auto-Configuration in Spring Boot?
Auto-Configuration is Spring Boot's mechanism to automatically configure your application based on the JAR dependencies present in the classpath. It uses the @EnableAutoConfiguration annotation (included in @SpringBootApplication).
How it works:
- Spring Boot scans
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports(orspring.factoriesin older versions) - Based on conditions (
@ConditionalOnClass,@ConditionalOnMissingBean, etc.), it registers beans automatically
Example: If spring-boot-starter-data-jpa is on the classpath, Spring Boot auto-configures a DataSource, EntityManagerFactory, and TransactionManager.
You can disable it using:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
Q6. What is @SpringBootApplication annotation and its internal working?
@SpringBootApplication is a convenience annotation that combines three annotations:
@SpringBootConfiguration // Marks as configuration class
@EnableAutoConfiguration // Enables auto-configuration
@ComponentScan // Scans for components in current package and sub-packages
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Internal working:
SpringApplication.run()bootstraps the application- Creates
ApplicationContext - Triggers
@EnableAutoConfigurationto load auto-config classes @ComponentScandiscovers all@Component,@Service,@Repository,@Controllerbeans- Starts the embedded server
Q7. Can we use Spring Boot for non-Spring applications?
No. Spring Boot is specifically designed to work with the Spring ecosystem. However, you can create non-web Spring Boot applications (without an embedded server) by setting:
spring.main.web-application-type=none
Or programmatically:
SpringApplication app = new SpringApplication(MyApplication.class);
app.setWebApplicationType(WebApplicationType.NONE);
app.run(args);
This is useful for batch jobs, CLI tools, and scheduled tasks.
Q8. How does Spring Boot work?
- Entry point is the
main()method annotated with@SpringBootApplication SpringApplication.run()creates anApplicationContext- Auto-configuration kicks in based on classpath dependencies
@ComponentScanregisters all beans- Embedded server (Tomcat by default) starts on port 8080
- Application is ready to handle requests
Spring Boot uses Condition-based configuration — beans are only created when specific conditions are met (e.g., certain class is on classpath, a property is set, a bean is missing).
Q9. What are the different options for creating a Spring Boot application?
- Spring Initializr (start.spring.io) — Web UI to generate project with selected dependencies
- Spring Boot CLI —
spring init --dependencies=web,jpa myproject - IDEs — IntelliJ IDEA, Eclipse (Spring Tools Suite), VS Code have built-in Spring Initializr support
- Maven/Gradle — Manually add spring-boot-starter-parent and dependencies
- Spring Tool Suite (STS) — Eclipse-based IDE with Spring project wizards
Q10. What is new in Spring Boot 2.0?
- Spring Framework 5.0 as base (reactive programming support)
- Java 8 minimum requirement (Java 9+ supported)
- Spring WebFlux — Reactive web framework
- Actuator redesign — REST-based endpoints, improved security
- Micrometer — Application metrics facade replacing Dropwizard Metrics
- Gradle 4 support
- Quartz Scheduler auto-configuration
- HikariCP as default connection pool (replacing Tomcat pool)
- Configuration property binding improvements
- HTTPS support improvements
2. Spring Boot Configuration & Setup
Q11. What is Spring Boot Initializer and its advantages?
Spring Initializr (start.spring.io) is a web-based tool that generates a Spring Boot project structure with selected dependencies.
Advantages:
- Generates project in seconds with proper directory structure
- Supports Maven and Gradle
- Lets you choose Spring Boot version, Java version, and packaging
- Pre-adds selected starter dependencies to
pom.xml/build.gradle - Available as web UI, IDE plugin, and CLI command
Q12. How to create a Spring Boot project using Spring Initializer?
- Visit start.spring.io
- Select: Project (Maven/Gradle), Language (Java), Spring Boot version
- Fill Group, Artifact, Name, Package name
- Select Dependencies (e.g., Spring Web, Spring Data JPA, H2)
- Click Generate → downloads a ZIP
- Extract and open in your IDE
- Run
mvn spring-boot:runor the main class
Q13. What is the purpose of application.properties/application.yml file?
It is the central configuration file for a Spring Boot application. It externalises configuration so you don't hardcode values in the source code.
Common uses:
# Server
server.port=8081
# Database
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
# JPA
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
# Logging
logging.level.org.springframework=DEBUG
Placed in src/main/resources/.
Q14. How to override default properties in Spring Boot?
Several ways in order of precedence (highest first):
- Command-line arguments:
java -jar app.jar --server.port=9090 - Environment variables:
SERVER_PORT=9090 - Profile-specific files:
application-prod.properties - application.properties/yml in
src/main/resources - Default values in auto-configuration classes
Q15. What is YAML in Spring Boot?
YAML (YAML Ain't Markup Language) is a human-readable data serialisation format used as an alternative to application.properties.
Properties vs YAML:
# application.properties
server.port=8081
spring.datasource.url=jdbc:mysql://localhost/db
spring.datasource.username=root
# application.yml
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost/db
username: root
YAML is preferred for hierarchical configuration and supports lists/maps natively.
Q16. How to use profiles in Spring Boot?
Profiles let you define different configurations for different environments (dev, test, prod).
Create profile-specific files:
application-dev.propertiesapplication-prod.properties
In YAML using --- separator:
spring:
profiles:
active: dev
---
spring:
config:
activate:
on-profile: dev
server:
port: 8080
---
spring:
config:
activate:
on-profile: prod
server:
port: 80
Q17. How to set active profile in Spring Boot?
Three ways:
- application.properties:
spring.profiles.active=prod
- Command line:
java -jar app.jar --spring.profiles.active=prod
- Environment variable:
export SPRING_PROFILES_ACTIVE=prod
Q18. What is the use of @Profile annotation?
@Profile marks a bean or configuration class to be loaded only when a specific profile is active.
@Configuration
@Profile("dev")
public class DevConfig {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().setType(H2).build();
}
}
@Configuration
@Profile("prod")
public class ProdConfig {
@Bean
public DataSource dataSource() {
// Production database config
}
}
Q19. How to get current profile in Spring Boot?
Inject Environment bean:
@Autowired
private Environment environment;
public void checkProfile() {
String[] profiles = environment.getActiveProfiles();
System.out.println("Active profiles: " + Arrays.toString(profiles));
}
Q20. Why do we need spring-boot-maven-plugin?
The spring-boot-maven-plugin packages the application into an executable fat JAR (uber JAR) that contains all dependencies and the embedded server.
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
Key goals:
spring-boot:run— Runs the applicationspring-boot:repackage— Creates executable JAR/WARspring-boot:build-info— Generates build information
Q21. How to disable specific auto-configuration in Spring Boot?
Option 1 — Annotation:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
Option 2 — Properties:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
Q22. What are the most common Spring Boot CLI commands?
spring init # Create new project
spring init --dependencies=web,jpa # With dependencies
spring run app.groovy # Run Groovy script
spring test app.groovy # Run tests
spring jar myapp.jar *.groovy # Package to JAR
spring help # Help
spring version # Show version
Q23. What is Spring Boot CLI and what are its benefits?
Spring Boot CLI is a command-line tool that allows running Spring Boot applications written in Groovy without a build tool.
Benefits:
- Run Spring apps without full project setup
- Groovy scripts auto-import Spring annotations
- Great for rapid prototyping
- Can generate new projects via Spring Initializr
- Supports running tests from command line
3. Dependency Management & Components
Q24. How does Spring Boot handle dependency management?
Spring Boot uses a parent POM (spring-boot-starter-parent) that imports a BOM (Bill of Materials) — spring-boot-dependencies — which defines compatible versions for hundreds of libraries.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>
This means you can add dependencies without specifying versions — Spring Boot picks the right compatible version automatically.
Q25. What are Spring Boot Starters?
Starters are pre-configured dependency descriptors that bundle all the libraries needed for a specific feature. They follow the naming convention spring-boot-starter-*.
<!-- Adds Spring MVC + embedded Tomcat + Jackson -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Q26. Name some starters provided by Spring Boot.
| Starter | Purpose |
|---|---|
spring-boot-starter-web | Spring MVC, REST APIs, embedded Tomcat |
spring-boot-starter-data-jpa | Spring Data JPA + Hibernate |
spring-boot-starter-security | Spring Security |
spring-boot-starter-test | JUnit, Mockito, Spring Test |
spring-boot-starter-actuator | Production monitoring |
spring-boot-starter-thymeleaf | Thymeleaf template engine |
spring-boot-starter-mail | Email with JavaMailSender |
spring-boot-starter-cache | Spring Cache abstraction |
spring-boot-starter-validation | Bean Validation (Hibernate Validator) |
spring-boot-starter-amqp | RabbitMQ messaging |
Q27. What is the purpose of the @ComponentScan annotation?
@ComponentScan tells Spring where to scan for components (beans annotated with @Component, @Service, @Repository, @Controller, etc.).
@ComponentScan(basePackages = "com.example")
// or
@ComponentScan(basePackageClasses = {MyService.class})
When using @SpringBootApplication, it automatically scans the package of the main class and all sub-packages.
Q28. What is component scanning?
Component scanning is the process by which Spring automatically detects and registers beans by scanning the classpath for classes annotated with stereotype annotations (@Component, @Service, @Repository, @Controller). It eliminates the need for explicit bean registration in XML or Java config.
Q29. Explain the difference between @Component, @Service, and @Repository annotations.
All three are specialisations of @Component — functionally similar, but semantically different:
| Annotation | Layer | Purpose |
|---|---|---|
@Component | Any | Generic Spring-managed bean |
@Service | Service layer | Business logic; no extra behaviour but signals intent |
@Repository | Data layer | DAO classes; adds exception translation (wraps JPA/JDBC exceptions into Spring's DataAccessException) |
@Controller | Web layer | MVC controller; handles HTTP requests |
Q30. What is Spring Bean?
A Spring Bean is any object that is instantiated, assembled, and managed by the Spring IoC (Inversion of Control) container. Beans are defined using @Component, @Bean, or XML configuration. The container manages their lifecycle — creation, dependency injection, and destruction.
Q31. What is Inner Bean in Spring?
An inner bean is a bean defined inside another bean's definition — used when the inner bean is only needed by one outer bean and has no need to be referenced elsewhere.
<bean id="outer" class="com.example.Outer">
<property name="inner">
<bean class="com.example.Inner"/> <!-- inner bean -->
</property>
</bean>
In Java config, inner beans are typically just created inline and not exposed as a named @Bean.
Q32. What is Bean Wiring?
Bean wiring is the process of connecting beans together — i.e., injecting dependencies. Spring supports:
- Auto-wiring — Spring resolves dependencies automatically (
@Autowired) - Manual wiring — Explicitly defining dependencies in XML or Java config
Q33. What is the use of @Configuration annotation?
@Configuration marks a class as a source of bean definitions. Methods annotated with @Bean inside a @Configuration class define beans managed by the Spring container.
@Configuration
public class AppConfig {
@Bean
public UserService userService() {
return new UserServiceImpl(userRepository());
}
@Bean
public UserRepository userRepository() {
return new UserRepositoryImpl();
}
}
Unlike @Component, @Configuration classes use CGLIB proxying to ensure @Bean methods always return the same singleton instance.
Q34. What is the purpose of @Bean annotation?
@Bean is used inside a @Configuration class to declare a method that returns a Spring-managed bean. The method name becomes the bean name by default.
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
Q35. Explain Bean scopes in Spring Boot.
| Scope | Description |
|---|---|
singleton (default) | One instance per Spring container |
prototype | New instance created every time the bean is requested |
request | One instance per HTTP request (web apps only) |
session | One instance per HTTP session (web apps only) |
application | One instance per ServletContext |
websocket | One instance per WebSocket session |
@Bean
@Scope("prototype")
public MyBean myBean() {
return new MyBean();
}
Q36. What is the purpose of @Value annotation?
@Value injects values from properties files, environment variables, or expressions into bean fields.
@Value("${server.port}")
private int port;
@Value("${app.name:DefaultApp}") // with default value
private String appName;
@Value("#{2 * T(Math).PI}") // SpEL expression
private double twoPi;
Q37. What is the purpose of @EnableAutoConfiguration annotation?
@EnableAutoConfiguration tells Spring Boot to automatically configure the application based on the JAR dependencies present on the classpath. It reads AutoConfiguration.imports files bundled in Spring Boot JARs and conditionally registers beans.
It is included in @SpringBootApplication, so you rarely use it directly.
4. Dependency Injection & Autowiring
Q38. What is Dependency Injection?
Dependency Injection (DI) is a design pattern where an object's dependencies are provided by an external entity (the IoC container) rather than the object creating them itself.
// Without DI — tightly coupled
public class OrderService {
private PaymentService paymentService = new PaymentService(); // bad
}
// With DI — loosely coupled
public class OrderService {
private final PaymentService paymentService;
public OrderService(PaymentService paymentService) { // injected
this.paymentService = paymentService;
}
}
Benefits: Loose coupling, easier testing, better maintainability.
Q39. What is Auto-wiring?
Auto-wiring is Spring's mechanism to automatically resolve and inject bean dependencies without explicitly defining them. Using @Autowired, Spring looks up the container for a matching bean by type (and by name if needed).
@Service
public class UserService {
@Autowired
private UserRepository userRepository; // Spring injects this
}
Q40. Explain Constructor Injection.
Dependencies are injected via the class constructor. Recommended approach for mandatory dependencies.
@Service
public class OrderService {
private final PaymentService paymentService;
private final InventoryService inventoryService;
// @Autowired is optional in Spring 4.3+ if only one constructor
public OrderService(PaymentService paymentService, InventoryService inventoryService) {
this.paymentService = paymentService;
this.inventoryService = inventoryService;
}
}
Advantages: Immutability, fail-fast (null dependencies cause startup failure), easier testing.
Q41. Explain Setter Injection.
Dependencies are injected via setter methods. Used for optional dependencies.
@Service
public class ReportService {
private EmailService emailService;
@Autowired
public void setEmailService(EmailService emailService) {
this.emailService = emailService;
}
}
Q42. Explain Field Injection.
Dependencies are injected directly into fields using @Autowired. Not recommended for production code (hard to test, hides dependencies).
@Service
public class UserService {
@Autowired
private UserRepository userRepository; // field injection
}
Q43. What is the difference between Constructor and Setter Injection?
| Feature | Constructor Injection | Setter Injection |
|---|---|---|
| Immutability | Supports (final fields) | Does not support |
| Mandatory dependencies | Enforced at startup | Not enforced |
| Circular dependency | Fails fast | Spring can resolve (with caution) |
| Testability | Easy (pass mocks in constructor) | Easy (call setter) |
| Recommended for | Mandatory dependencies | Optional dependencies |
Q44. What is the purpose of @Autowired annotation?
@Autowired marks a constructor, field, or setter method for automatic dependency injection by Spring. Spring resolves the dependency by type. If multiple beans of the same type exist, use @Qualifier to specify which one.
@Autowired
@Qualifier("mysqlDataSource")
private DataSource dataSource;
Q45. What is IOC container?
The IoC (Inversion of Control) container is the core of Spring. It manages the lifecycle of beans — instantiation, configuration, and assembly. The "inversion" refers to the fact that the framework calls your code (via DI) rather than your code instantiating its dependencies.
Two types in Spring:
BeanFactory— Basic container, lazy loadingApplicationContext— Extended container (preferred), eager loading, adds event handling, AOP, i18n
5. Web Layer & MVC
Q46. What is Spring MVC?
Spring MVC is a web framework built on the Servlet API that follows the Model-View-Controller design pattern. It provides:
DispatcherServletas the front controller- Handler mappings to route requests to controllers
- View resolvers to render responses
- Full support for RESTful APIs
Q47. Explain the flow of Spring MVC.
- Client sends HTTP request
- DispatcherServlet receives request (front controller)
- HandlerMapping determines which controller to call
- Controller processes request, returns
ModelAndView - ViewResolver resolves the logical view name to an actual view
- View renders the response
- Response sent back to Client
For REST APIs, step 5-6 are replaced by @ResponseBody — Jackson serialises the object to JSON directly.
Q48. What is Dispatcher Servlet?
DispatcherServlet is the front controller of Spring MVC. It is a single central servlet that receives all HTTP requests, delegates to appropriate handlers (controllers), and returns the response.
Spring Boot auto-configures DispatcherServlet at the path / by default. You can override:
spring.mvc.servlet.path=/api
Q49. What is the difference between @Controller and @RestController?
| Feature | @Controller | @RestController |
|---|---|---|
| Returns | View name (template) | Object serialised to JSON/XML |
| @ResponseBody | Must add manually | Included by default |
| Use case | Traditional MVC with views | REST APIs |
@RestController = @Controller + @ResponseBody
Q50. What is the use of @Controller annotation?
@Controller marks a class as a Spring MVC controller that handles HTTP requests. Methods return view names resolved by a ViewResolver to render HTML templates (e.g., Thymeleaf). Use @ResponseBody on methods when returning data instead of view names.
Q51. What is the purpose of @RestController annotation?
@RestController is a specialisation of @Controller for building RESTful APIs. It combines @Controller and @ResponseBody, so every method automatically serialises the return value to JSON/XML and writes it to the HTTP response body.
Q52. Explain @GetMapping and @PostMapping.
Shorthand annotations for @RequestMapping with specific HTTP methods:
@GetMapping("/users") // GET /users
public List<User> getUsers() { ... }
@PostMapping("/users") // POST /users
public User createUser(@RequestBody User user) { ... }
@PutMapping("/users/{id}") // PUT /users/1
public User updateUser(@PathVariable Long id, @RequestBody User user) { ... }
@DeleteMapping("/users/{id}") // DELETE /users/1
public void deleteUser(@PathVariable Long id) { ... }
Q53. What is the difference between @RequestMapping and @GetMapping?
@RequestMapping is the general-purpose mapping annotation that works for all HTTP methods. @GetMapping is a composed annotation specifically for GET requests.
@RequestMapping(value = "/users", method = RequestMethod.GET) // verbose
@GetMapping("/users") // concise equivalent
Q54. Difference between @RequestParam and @PathVariable.
| Feature | @RequestParam | @PathVariable |
|---|---|---|
| Source | Query string (?key=value) | URL path (/users/{id}) |
| Optional | Can be (required=false) | Usually required |
| Example URL | /users?id=1 | /users/1 |
@GetMapping("/search")
public List<User> search(@RequestParam String name) { ... }
// URL: /search?name=John
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) { ... }
// URL: /users/42
Q55. What is the purpose of @ModelAttribute?
@ModelAttribute binds HTTP form data or query parameters to a Java object (model). It can be used:
- On method parameters — binds request data to an object
- On methods — populates model attributes available to all handler methods in the controller
@PostMapping("/register")
public String register(@ModelAttribute UserForm form) {
// form fields automatically populated from request
}
Q56. How does Spring MVC support validation?
Spring MVC integrates with Bean Validation (JSR-380) via Hibernate Validator. Use @Valid or @Validated on method parameters:
public class User {
@NotBlank
private String name;
@Email
private String email;
@Min(18)
private int age;
}
@PostMapping("/users")
public ResponseEntity<User> create(@Valid @RequestBody User user, BindingResult result) {
if (result.hasErrors()) {
// handle validation errors
}
return ResponseEntity.ok(userService.save(user));
}
Q57. What is the use of @ResponseEntity annotation?
ResponseEntity represents the full HTTP response — status code, headers, and body. It gives you full control over the response.
@GetMapping("/users/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
return userService.findById(id)
.map(user -> ResponseEntity.ok(user))
.orElse(ResponseEntity.notFound().build());
}
Q58. What is RESTful API in Spring Boot?
A RESTful API follows REST (Representational State Transfer) architectural constraints:
- Stateless client-server communication
- Uses HTTP methods (GET, POST, PUT, DELETE)
- Resources identified by URIs
- JSON/XML for data exchange
Spring Boot makes REST API development easy with @RestController, @RequestMapping, and Jackson auto-configuration.
Q59. What is the purpose of @Scheduled annotation?
@Scheduled marks a method to run on a schedule. Requires @EnableScheduling on a configuration class.
@Scheduled(fixedRate = 5000) // every 5 seconds
@Scheduled(cron = "0 0 9 * * MON") // every Monday at 9am
@Scheduled(fixedDelay = 1000) // 1 second after last execution ends
public void performTask() {
System.out.println("Running scheduled task");
}
Q60. What is Thymeleaf?
Thymeleaf is a server-side Java HTML template engine used with Spring MVC. It processes templates at runtime, rendering dynamic HTML pages.
<!-- index.html -->
<h1 th:text="${message}">Default Message</h1>
<ul>
<li th:each="user : ${users}" th:text="${user.name}"></li>
</ul>
It is natural templating — the HTML file can be opened in a browser as a static prototype too.
Q61. Describe the flow of HTTPS requests through Spring Boot application.
- Client sends HTTPS request (TLS handshake happens first)
- Request reaches the embedded Tomcat server on port 443 (or 8443)
- TLS terminates — request decrypted
- DispatcherServlet receives the plain HTTP request
- Request goes through Filter chain (security filters, logging, etc.)
- HandlerMapping routes to the right Controller method
- Controller processes and returns response
- Response goes through filters, serialised to JSON
- Tomcat encrypts response via TLS and sends to client
6. Data Access Layer
Q62. What is Spring Data JPA?
Spring Data JPA is part of the larger Spring Data family. It reduces boilerplate data access code by providing repository abstractions on top of JPA (Java Persistence API). You define interfaces extending JpaRepository, and Spring generates the implementation at runtime.
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByEmail(String email);
Optional<User> findByUsername(String username);
}
No SQL or JPQL needed for simple queries — Spring Data derives them from the method name.
Q63. Explain features of Spring Data JPA.
- Repository abstraction —
CrudRepository,JpaRepository,PagingAndSortingRepository - Query derivation — Method names like
findByFirstNameAndLastNameauto-generate queries - Custom JPQL/Native queries — via
@Queryannotation - Pagination and Sorting — built-in
Pageablesupport - Auditing —
@CreatedDate,@LastModifiedDateauto-populated - Projections — Interface-based or DTO projections for partial data
- Specifications — Type-safe dynamic queries
Q64. What is the use of @EnableJpaRepositories annotation?
@EnableJpaRepositories enables JPA repository scanning. It tells Spring where to look for repository interfaces.
@Configuration
@EnableJpaRepositories(basePackages = "com.example.repository")
public class JpaConfig { }
In Spring Boot, this is auto-configured, so you rarely need it explicitly.
Q65. How to create a custom Repository in Spring JPA?
// Define interface
public interface UserRepository extends JpaRepository<User, Long> {
// Query derivation
List<User> findByCity(String city);
// Custom JPQL query
@Query("SELECT u FROM User u WHERE u.email = :email")
Optional<User> findByEmailAddress(@Param("email") String email);
// Native SQL query
@Query(value = "SELECT * FROM users WHERE active = 1", nativeQuery = true)
List<User> findAllActiveUsers();
}
Q66. Difference between CRUDRepository and JPARepository.
| Feature | CrudRepository | JpaRepository |
|---|---|---|
| Basic CRUD | ✅ | ✅ |
| Pagination | ❌ | ✅ (findAll(Pageable)) |
| Sorting | ❌ | ✅ |
| Flush/delete in batch | ❌ | ✅ |
getOne() (reference) | ❌ | ✅ |
| Extends | Repository | PagingAndSortingRepository → CrudRepository |
Use JpaRepository unless you need a minimal interface.
Q67. Explain common CrudRepository methods.
repository.save(entity); // INSERT or UPDATE
repository.saveAll(entities); // Batch save
repository.findById(id); // SELECT by primary key → Optional
repository.findAll(); // SELECT all
repository.count(); // COUNT(*)
repository.existsById(id); // EXISTS check
repository.deleteById(id); // DELETE by id
repository.delete(entity); // DELETE by entity
repository.deleteAll(); // DELETE all
Q68. What is the purpose of save() method in CrudRepository?
save() performs an upsert — if the entity has a null or non-existent ID, it does an INSERT; if the entity already has an ID that exists in the database, it does an UPDATE (merge).
It delegates to EntityManager.persist() for new entities and EntityManager.merge() for existing ones.
Q69. Difference between findById() and getOne().
| Feature | findById() | getOne() / getById() |
|---|---|---|
| Returns | Optional<T> | T (proxy) |
| DB hit | Immediate SELECT | Lazy — only when proxy is accessed |
| Exception | Returns empty Optional | Throws EntityNotFoundException if not found when accessed |
| Recommended | ✅ Yes | For use in relationships only |
Q70. Difference between delete() and deleteInBatch() methods.
| Feature | delete() | deleteInBatch() |
|---|---|---|
| Loads entity first | Yes (SELECT then DELETE) | No |
| Cascades | Yes (respects JPA cascade) | No |
| Performance | Slower (N+1 issue possible) | Faster (single DELETE statement) |
| Use case | When cascade delete needed | Bulk deletes without cascade |
Q71. What is the use of @Modifying annotation?
@Modifying is used with @Query to indicate that the query modifies data (UPDATE/DELETE). Without it, Spring Data throws an exception.
@Modifying
@Transactional
@Query("UPDATE User u SET u.active = false WHERE u.lastLogin < :date")
int deactivateInactiveUsers(@Param("date") LocalDate date);
Q72. Explain @Transactional annotation in Spring.
@Transactional marks a method or class to run within a database transaction. Spring creates a transaction before the method starts and commits/rolls back when it ends.
@Transactional
public void transferMoney(Long fromId, Long toId, BigDecimal amount) {
accountRepository.debit(fromId, amount); // both succeed
accountRepository.credit(toId, amount); // or both roll back
}
Key attributes:
propagation— REQUIRED (default), REQUIRES_NEW, NESTED, etc.isolation— READ_COMMITTED (default), SERIALIZABLE, etc.rollbackFor— Which exceptions trigger rollbackreadOnly— Optimisation hint for read-only transactions
Q73. What is Spring Data REST?
Spring Data REST automatically exposes Spring Data repositories as RESTful endpoints — no controller code needed.
@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRepository extends JpaRepository<User, Long> {}
This auto-creates: GET /users, POST /users, GET /users/{id}, PUT /users/{id}, DELETE /users/{id}.
Q74. Why is Spring Data REST not recommended in real-world applications?
- Exposes internal domain model directly — any schema change breaks API contracts
- No business logic layer — validation, authorisation, transformations are hard to add
- HATEOAS by default — response format is opinionated and harder to consume
- Limited control over the API shape, HTTP status codes, and error responses
- Security concerns — easy to accidentally expose sensitive data
Better to write explicit controllers with DTOs for production APIs.
Q75. How is Hibernate chosen as the default JPA implementation without any configuration?
When spring-boot-starter-data-jpa is on the classpath, it transitively includes hibernate-core. Spring Boot's auto-configuration detects Hibernate on the classpath and auto-configures:
HibernateJpaAutoConfigurationEntityManagerFactoryusing HibernateTransactionManager
No explicit configuration is needed — convention over configuration.
Q76. What error do you see if H2 is not present in the classpath?
If spring.datasource.url is not configured and no database driver is on the classpath, you get:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Fix: Either add H2 dependency for embedded DB, or configure spring.datasource.* properties for a real database.
Q77. Mention the steps to connect Spring Boot application to a database using JDBC.
- Add dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
- Configure
application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- Use
JdbcTemplate:
@Autowired
private JdbcTemplate jdbcTemplate;
public List<User> findAll() {
return jdbcTemplate.query("SELECT * FROM users",
(rs, row) -> new User(rs.getLong("id"), rs.getString("name")));
}
7. Security
Q78. What is Spring Security?
Spring Security is a powerful, customisable authentication and access-control framework for Java applications. It provides:
- Authentication (who are you?)
- Authorisation (what can you do?)
- Protection against common attacks (CSRF, session fixation, XSS headers)
It integrates seamlessly with Spring Boot via spring-boot-starter-security.
Q79. What are the features of Spring Security?
- Comprehensive authentication support (form login, HTTP Basic, OAuth2, JWT, LDAP)
- Role-based and expression-based access control
- Method-level security (
@PreAuthorize,@PostAuthorize) - CSRF protection enabled by default
- Session management (concurrent session control, session fixation protection)
- Remember-me authentication
- Integration with Spring MVC and Spring WebFlux
- Password encoding (
BCryptPasswordEncoder) - OAuth2 / OpenID Connect support
Q80. How to implement security for Spring Boot application?
- Add dependency:
spring-boot-starter-security - Configure
SecurityFilterChain:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.formLogin(Customizer.withDefaults())
.logout(Customizer.withDefaults());
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Q81. How to enable Spring Boot security?
Simply add the dependency — Spring Boot auto-configures basic security (form login, random password printed to console):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
To customise, create a SecurityFilterChain bean as shown above.
Q82. What is Basic Authentication?
HTTP Basic Authentication sends credentials (username:password) Base64-encoded in the Authorization header on every request.
Authorization: Basic dXNlcjpwYXNzd29yZA==
Not secure over HTTP (Base64 is not encryption). Always use with HTTPS. Spring Security supports it via .httpBasic().
Q83. What is Digest Authentication?
Digest Authentication is an improvement over Basic Auth where the password is never sent in plain text. Instead, a hash (MD5) of the credentials is sent. However, it is considered weak by modern standards and is rarely used. JWT or OAuth2 are preferred today.
Q84. What is JWT and its advantages?
JWT (JSON Web Token) is a compact, self-contained token for securely transmitting information between parties as a JSON object.
Structure: header.payload.signature
Advantages:
- Stateless — No server-side session storage needed
- Scalable — Works well in distributed/microservice systems
- Self-contained — Token carries user info (claims)
- Cross-domain — Works across different domains (no cookie restrictions)
- Mobile-friendly — Easier to use in mobile/API clients than cookies
Q85. How to implement JWT?
- Add dependency:
jjwt-api,jjwt-impl,jjwt-jackson - Create
JwtUtilto generate and validate tokens:
public String generateToken(UserDetails userDetails) {
return Jwts.builder()
.setSubject(userDetails.getUsername())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 86400000))
.signWith(secretKey)
.compact();
}
- Create
JwtAuthenticationFilterextendingOncePerRequestFilter - Validate token, extract user, set
SecurityContextHolder - Register filter in
SecurityFilterChainbeforeUsernamePasswordAuthenticationFilter
Q86. What is Spring Security OAuth2?
Spring Security OAuth2 provides support for implementing OAuth2 authorization framework — both as a resource server (protecting APIs) and as a client (delegating authentication to providers like Google, GitHub, Okta).
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.oauth2Login(Customizer.withDefaults()) // Login with Google/GitHub
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())); // Validate JWT
return http.build();
}
Q87. What is authentication vs authorization?
| Authentication | Authorization | |
|---|---|---|
| Question | Who are you? | What can you do? |
| Process | Verify identity (login) | Check permissions |
| Example | Username + password check | "Admin" role can delete users |
| Spring | AuthenticationManager | AccessDecisionManager / @PreAuthorize |
Authentication happens first, authorization second.
Q88. What is SecurityContext in Spring Security?
SecurityContext holds the Authentication object of the currently authenticated user. It is stored in SecurityContextHolder (thread-local by default).
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();
Collection<? extends GrantedAuthority> roles = auth.getAuthorities();
Q89. How to get current logged-in user in Spring Security?
// Option 1 — SecurityContextHolder
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();
// Option 2 — @AuthenticationPrincipal in controller
@GetMapping("/profile")
public UserDto getProfile(@AuthenticationPrincipal UserDetails userDetails) {
return userService.findByUsername(userDetails.getUsername());
}
Q90. What is AuthenticationManager?
AuthenticationManager is the main interface for authentication in Spring Security. Its authenticate() method processes an Authentication request and returns a fully populated Authentication object (including granted authorities) if authentication succeeds.
The default implementation is ProviderManager, which delegates to a chain of AuthenticationProvider instances.
Q91. What is DelegatingFilterProxy?
DelegatingFilterProxy is a Servlet Filter that delegates to a Spring bean that implements the Filter interface. It bridges the gap between the Servlet container lifecycle and Spring's ApplicationContext.
Spring Security uses it to inject its FilterChainProxy bean into the Servlet filter chain.
Q92. What is FilterChainProxy?
FilterChainProxy is a special Spring Security filter that manages a list of SecurityFilterChain instances. It routes incoming requests to the appropriate SecurityFilterChain based on the request path. This is the bean that DelegatingFilterProxy delegates to.
Q93. Difference between hasAuthority and hasRole?
| hasAuthority | hasRole | |
|---|---|---|
| Prefix | Exact match | Automatically prepends ROLE_ |
| Example | hasAuthority("ADMIN") | hasRole("ADMIN") matches ROLE_ADMIN |
| GrantedAuthority | ADMIN | ROLE_ADMIN |
| Use case | Fine-grained permissions | Role-based access |
Q94. What is SSL and its use?
SSL (Secure Sockets Layer) / TLS (Transport Layer Security) is a cryptographic protocol that provides encrypted communication between a client and server. In Spring Boot, enable HTTPS by:
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=changeit
server.ssl.key-store-type=PKCS12
server.ssl.key-alias=myapp
server.port=8443
Q95. What is salting?
Salting is the practice of adding a random string (salt) to a password before hashing it. This prevents:
- Rainbow table attacks — Precomputed hash tables become useless
- Identical passwords from having identical hashes
BCryptPasswordEncoder automatically generates and stores a unique salt per password.
Q96. What is hashing in Spring Security?
Hashing converts a password into a fixed-length irreversible string. Spring Security's PasswordEncoder interface handles this. BCryptPasswordEncoder is recommended — it is slow by design (making brute-force expensive) and includes automatic salting.
PasswordEncoder encoder = new BCryptPasswordEncoder();
String hash = encoder.encode("mypassword");
boolean matches = encoder.matches("mypassword", hash); // true
Q97. How to secure passwords in a web application?
- Never store plain text passwords
- Use
BCryptPasswordEncoder(work factor 10-12) - Use HTTPS to protect passwords in transit
- Implement account lockout after N failed attempts
- Use CSRF tokens for form submissions
- Enforce strong password policies
- Implement multi-factor authentication (MFA) for sensitive apps
- Hash passwords before storing even with parameterised queries
Q98. What are the various ways to implement security in Spring Boot?
- Spring Security — Full-featured security framework (recommended)
- JWT — Stateless token-based auth for REST APIs
- OAuth2/OpenID Connect — Delegate auth to Google, GitHub, Okta
- API Key — Simple key in header for server-to-server communication
- Basic Authentication — Username/password in header (HTTPS only)
- Method-level security —
@PreAuthorize,@Securedon service methods
8. Monitoring & Actuator
Q99. What is Spring Boot Actuator?
Spring Boot Actuator provides production-ready features to monitor and manage your application via HTTP endpoints or JMX. It exposes information like health, metrics, environment, beans, logging levels, and more — without writing any code.
Add: spring-boot-starter-actuator
Q100. How to enable actuator in Spring Boot?
Add the dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Access: http://localhost:8080/actuator
By default, only /actuator/health and /actuator/info are exposed over HTTP.
Q101. What are the actuator endpoints for monitoring?
| Endpoint | Description |
|---|---|
/actuator/health | Application health status |
/actuator/info | App info (from application.properties) |
/actuator/metrics | Application metrics |
/actuator/env | Environment properties |
/actuator/beans | All Spring beans |
/actuator/mappings | All @RequestMapping paths |
/actuator/loggers | Logger levels (can change at runtime) |
/actuator/threaddump | Current thread dump |
/actuator/heapdump | Heap dump file |
/actuator/shutdown | Graceful shutdown (disabled by default) |
Q102. How to enable all endpoints in actuator?
# Expose all endpoints over HTTP
management.endpoints.web.exposure.include=*
# Or specific endpoints
management.endpoints.web.exposure.include=health,info,metrics,env
# Change actuator base path
management.endpoints.web.base-path=/manage
⚠️ Security warning: Never expose all actuator endpoints in production without authentication.
Q103. What is shutdown in actuator?
/actuator/shutdown is an endpoint that allows graceful application shutdown via an HTTP POST request. It is disabled by default for security reasons.
management.endpoint.shutdown.enabled=true
curl -X POST http://localhost:8080/actuator/shutdown
Q104. How to get the list of beans available in Spring application?
Use the /actuator/beans endpoint (requires it to be exposed):
management.endpoints.web.exposure.include=beans
Or programmatically:
@Autowired
private ApplicationContext context;
public void listBeans() {
Arrays.stream(context.getBeanDefinitionNames())
.forEach(System.out::println);
}
Q105. How to check environment properties in Spring Boot application?
- Actuator endpoint:
GET /actuator/env— shows all environment properties @Valueannotation — inject specific property values directly
Programmatically using Environment:
@Autowired
private Environment env;
String port = env.getProperty("server.port");
9. Development Tools & Deployment
Q106. What are Spring Boot DevTools used for?
spring-boot-devtools improves the development experience:
- Automatic restart when classpath files change
- LiveReload support (browser auto-refresh)
- Remote debugging support
- Development-time property defaults (e.g., disables template caching)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
Q107. How can I reload Spring Boot changes without restarting the server?
Using Spring Boot DevTools — it monitors the classpath and triggers a fast restart when it detects changes. Combined with your IDE's build-on-save:
- Add devtools dependency
- Enable "Build project automatically" in IntelliJ (or save in Eclipse)
- Application restarts in ~1-2 seconds (faster than cold start because it reuses a base classloader)
Q108. What are the embedded containers supported by Spring Boot?
| Container | Starter |
|---|---|
| Tomcat (default) | spring-boot-starter-web |
| Jetty | Exclude Tomcat, add spring-boot-starter-jetty |
| Undertow | Exclude Tomcat, add spring-boot-starter-undertow |
| Reactor Netty (reactive) | spring-boot-starter-webflux |
Q109. How to run Spring Boot application on a custom port?
server.port=9090
Or via command line:
java -jar app.jar --server.port=9090
To use a random port (e.g., for tests):
server.port=0
Q110. How to override or replace the embedded Tomcat server?
Exclude Tomcat and add Jetty:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
Q111. Can we create a non-web application in Spring Boot?
Yes. Set the web application type to NONE:
spring.main.web-application-type=none
Or in code:
SpringApplication app = new SpringApplication(MyApp.class);
app.setWebApplicationType(WebApplicationType.NONE);
app.run(args);
Useful for batch processing, scheduled jobs, CLI tools.
Q112. How to generate a WAR file with Spring Boot?
- Change packaging in
pom.xml:
<packaging>war</packaging>
- Extend
SpringBootServletInitializer:
@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(MyApplication.class);
}
}
- Mark embedded Tomcat as provided:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
- Run
mvn package→ generates.warintarget/
Q113. How to include custom static content in Spring Boot?
Place static files in:
src/main/resources/static/src/main/resources/public/src/main/resources/resources/src/main/resources/META-INF/resources/
Files in these locations are served directly. E.g., static/js/app.js → http://localhost:8080/js/app.js
To add custom locations:
spring.web.resources.static-locations=classpath:/custom-static/
Q114. How to configure database using Spring Boot?
# MySQL
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# JPA
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
Spring Boot auto-configures HikariCP connection pool with these properties.
Q115. What is the default port of Tomcat in Spring Boot?
8080. Change with:
server.port=9090
Q116. Can we disable the default web server in Spring Boot application?
Yes:
spring.main.web-application-type=none
Or exclude the web starter and use only non-web starters.
Q117. What are the differences between WAR and embedded containers?
| Feature | WAR (External Server) | Embedded Container |
|---|---|---|
| Deployment | Deploy to Tomcat/JBoss/WebLogic | Run as standalone JAR |
| Server management | Ops team manages server | Dev team manages |
| Startup | Depends on server | java -jar app.jar |
| Portability | Tied to server version | Self-contained |
| Microservices | Less suitable | Ideal |
| Cloud deployment | Harder | Easy (containers, PaaS) |
Q118. How to deploy to a different server with Spring Boot?
- Package as WAR (see Q112)
- Copy WAR to the server's
webapps/directory (Tomcat) or equivalent - Or configure deployment in Tomcat Manager
For cloud deployments, package as JAR and use Docker:
FROM eclipse-temurin:17-jre
COPY target/app.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
10. Exception Handling & Logging
Q119. How to handle exceptions in Spring MVC?
Three approaches:
@ExceptionHandlerin controller — handles exceptions for that controller only@ControllerAdvice— global exception handler across all controllersResponseEntityExceptionHandler— extend this for default Spring MVC exceptions
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(404)
.body(new ErrorResponse("NOT_FOUND", ex.getMessage()));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGeneral(Exception ex) {
return ResponseEntity.status(500)
.body(new ErrorResponse("INTERNAL_ERROR", "Something went wrong"));
}
}
Q120. Explain @ControllerAdvice in Spring Boot.
@ControllerAdvice is a specialisation of @Component that allows classes to handle exceptions, bind data, or add model attributes globally across all controllers (or a subset defined by basePackages).
Most commonly used with @ExceptionHandler to create a centralised error handling mechanism.
Q121. What is the purpose of @RestControllerAdvice?
@RestControllerAdvice = @ControllerAdvice + @ResponseBody
Used for REST APIs — exception handler methods automatically serialise the return value to JSON without needing @ResponseBody on each method.
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Map<String, String> handleNotFound(NotFoundException ex) {
return Map.of("error", ex.getMessage());
}
}
Q122. What logging support is provided by Spring Boot?
Spring Boot uses SLF4J as the logging facade and Logback as the default logging implementation. It auto-configures:
- Console logging at INFO level
- Colour-coded output in supported terminals
- Log rotation and archival
Supported frameworks: Logback (default), Log4j2, JUL (Java Util Logging)
private static final Logger log = LoggerFactory.getLogger(MyService.class);
// or with Lombok:
@Slf4j
public class MyService { }
Q123. How to control logging level in Spring Boot?
# Set root level
logging.level.root=WARN
# Set package level
logging.level.com.example=DEBUG
logging.level.org.springframework.web=INFO
logging.level.org.hibernate.SQL=DEBUG
# Log to file
logging.file.name=app.log
logging.file.path=/var/log/myapp
Change at runtime via Actuator:
curl -X POST http://localhost:8080/actuator/loggers/com.example \
-H "Content-Type: application/json" \
-d '{"configuredLevel": "DEBUG"}'
Q124. How to enable debugging log in Spring Boot?
# Enable debug logging
logging.level.root=DEBUG
# Or only for Spring framework
debug=true
Command line:
java -jar app.jar --debug
The --debug flag enables auto-configuration report showing which auto-configs were applied and why.
11. Advanced Concepts
Q125. What is Spring Cloud?
Spring Cloud provides tools for building distributed systems and microservices. Built on top of Spring Boot, it offers:
| Component | Purpose |
|---|---|
| Eureka | Service discovery (register and find services) |
| Spring Cloud Gateway | API gateway, routing, filtering |
| Config Server | Centralised external configuration |
| Resilience4j | Circuit breaker, retry, rate limiter |
| Spring Cloud Sleuth | Distributed tracing |
| OpenFeign | Declarative REST client |
| Spring Cloud Stream | Message-driven microservices (Kafka, RabbitMQ) |
Q126. What is AOP (Aspect-Oriented Programming)?
AOP is a programming paradigm that allows separating cross-cutting concerns (logging, security, transactions, caching) from the business logic.
Key concepts:
- Aspect — The cross-cutting concern (e.g., logging)
- Advice — What to do (Before, After, Around, AfterReturning, AfterThrowing)
- Pointcut — Where to apply (expression matching method signatures)
- JoinPoint — A point in the program (method execution)
@Aspect
@Component
public class LoggingAspect {
@Around("execution(* com.example.service.*.*(..))")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
log.info("{} executed in {}ms", joinPoint.getSignature(), System.currentTimeMillis() - start);
return result;
}
}
Q127. What is a Runner and its types (ApplicationRunner vs CommandLineRunner)?
Runners are interfaces that allow running code after the Spring ApplicationContext is fully initialised.
// ApplicationRunner — receives ApplicationArguments
@Component
public class MyRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
System.out.println("App started! Options: " + args.getOptionNames());
}
}
// CommandLineRunner — receives raw String[] args
@Component
public class MyCliRunner implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("App started! Args: " + Arrays.toString(args));
}
}
Use for: data seeding, connectivity checks, banner printing, initial scheduled job trigger.
Q128. How to implement SSL/HTTPS in Spring Boot?
- Generate a keystore:
keytool -genkeypair -alias myapp -keyalg RSA -keysize 2048 \
-storetype PKCS12 -keystore keystore.p12 -validity 365
Place
keystore.p12insrc/main/resources/Configure
application.properties:
server.port=8443
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=yourpassword
server.ssl.key-store-type=PKCS12
server.ssl.key-alias=myapp
- To redirect HTTP to HTTPS, add a connector bean in configuration.
Q129. What are the advantages of YAML over Properties file?
| Feature | Properties | YAML |
|---|---|---|
| Hierarchy | Repeated keys (a.b.c=1) | Natural nesting |
| Lists | list[0]=a | - a |
| Readability | Lower for complex config | Higher |
| Multi-document | Not supported | --- separator |
| Comments | # | # |
Ways to load YAML in Spring Boot:
- Default:
application.ymlauto-loaded @PropertySource+YamlPropertiesFactoryBeanfor custom files@ConfigurationPropertiesbound to YAML subtrees
Q130. REST and HTTP fundamentals.
HTTP Methods:
| Method | Purpose | Idempotent? |
|---|---|---|
| GET | Read resource | Yes |
| POST | Create resource | No |
| PUT | Replace resource | Yes |
| PATCH | Partial update | No |
| DELETE | Delete resource | Yes |
| Code | Meaning |
|---|---|
| 200 | OK |
| 201 | Created |
| 204 | No Content |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 500 | Internal Server Error |
- Stateless — each request is self-contained
- Client-Server separation
- Cacheable responses
- Uniform interface (standard HTTP verbs + resource URIs)
- Layered system
Struggling to Find a Job? These Startups Are Hiring ✅ Startup list