Spring Boot Interview Questions with Dertailed Answers
Spring Boot Interview Questions with Dertailed Answers
Table of Contents
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2. What are the main features and advantages of using Spring Boot for application
development?
• Auto-configuration:
Auto-configuration in Spring Boot is one of its key features that simplifies application
setup. In traditional Spring, when setting up a project, developers had to manually
configure both their own classes and the Spring-provided classes, such as data sources,
transaction managers, or web servers. This often involved a significant amount of
boilerplate code.
For instance, if a developer includes a dependency like Spring Data JPA in their project,
Spring Boot will automatically configure a DataSource and other related beans, such as
EntityManagerFactory, without needing to manually define them in configuration files.
The focus is now solely on configuring only the custom beans (i.e., the classes specific to
the application), reducing boilerplate and letting developers concentrate on the
application’s business logic instead of infrastructure concerns.
• Embedded Servers: Spring Boot comes with embedded servers like Tomcat, Jetty, or
Undertow, so you don’t need to deploy WAR files or set up an external server.
• Spring Boot Actuator: It includes built-in production-ready features like health checks,
metrics, application monitoring, and externalized configuration.
• Starter Dependencies: Spring Boot simplifies dependency management with a set of
curated, versioned dependencies that work well together.
• Spring Boot CLI: A command-line interface for running and testing Spring Boot
applications quickly, allowing you to write Groovy scripts and start applications with
minimal setup.
• Spring Boot DevTools: Provides a set of tools to improve the development experience,
such as automatic restarts, live reload, and enhanced logging, to speed up development
cycles.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
i. @Configuration: Marks the class as a source of bean definitions for the application
context. It is equivalent to using XML configuration in traditional Spring, but in a
more concise and Java-based way.
ii. @EnableAutoConfiguration: Tells Spring Boot to automatically configure the
application based on the dependencies present in the classpath. This reduces the
need for manual configuration and setup, making it easier to create production-
ready applications.
iii. @ComponentScan: Tells Spring to scan the package (and sub-packages) for
components, configurations, and services. This allows Spring to discover and register
beans, such as @Controller, @Service, @Repository, etc.
To externalize configuration in Spring Boot, you can use the following methods:
@Value("${company.maxEmployees}")
private int maxEmployees;
Example: spring.profiles.active=dev
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/greet")
public String greet() {
return "Hello, World!";
}
}
@RestController
public class UserController {
@GetMapping("/users")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
}
13. How to handle HTTP request methods like GET, POST, PUT, DELETE in Spring Boot?
Answer: Use @GetMapping, @PostMapping, @PutMapping, @DeleteMapping to map
HTTP methods to handler methods.
Example:
@PostMapping("/users")
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
17. How can you configure and use multiple databases in a Spring Boot application?
To use multiple databases in Spring Boot, you need to configure multiple data sources
and create separate DataSource, EntityManagerFactory, and TransactionManager beans
for each database. Here's how you can do it:
@Configuration
Pavan Kumar | www.javadzone.com 9
@EnableTransactionManagement
public class DataSourceConfig {
@Primary
@Bean(name = "primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "primaryEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier("primaryDataSource") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("com.example.model.primary") // package containing primary DB
entities
.persistenceUnit("primary")
.build();
}
@Bean(name = "secondaryEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier("secondaryDataSource") DataSource dataSource) {
return builder
.dataSource(dataSource)
@Primary
@Bean(name = "primaryTransactionManager")
public PlatformTransactionManager primaryTransactionManager(
@Qualifier("primaryEntityManagerFactory") EntityManagerFactory
entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
@Bean(name = "secondaryTransactionManager")
public PlatformTransactionManager secondaryTransactionManager(
@Qualifier("secondaryEntityManagerFactory") EntityManagerFactory
entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
Define Repositories:
@Configuration
@EnableJpaRepositories(
basePackages = "com.example.repository.primary",
entityManagerFactoryRef = "primaryEntityManagerFactory",
transactionManagerRef = "primaryTransactionManager"
)
public class PrimaryDatabaseConfig {}
@Entity
public class User {
@Id
private Long id;
private String name;
}
When a class is annotated with @Repository, Spring automatically handles the class as a Spring
bean, making it eligible for component scanning. Additionally, @Repository provides automatic
There are several ways to implement security in a Spring Boot application. The primary
methods include:
i. Spring Security:
a. Spring Security is the most common and comprehensive way to implement
security in Spring Boot. It provides authentication, authorization, and various
other security features like CSRF protection, HTTP Basic authentication,
OAuth2, and more.
b. You can configure it using either Java configuration (@EnableWebSecurity and
WebSecurityConfigurerAdapter) or by using custom filters and handlers.
ii. Basic Authentication:
a. Basic authentication is a simple method where the client sends a username
and password with each HTTP request.
b. Spring Security can be configured to use HTTP Basic authentication with simple
configurations in application.properties or through Java config.
iii. JWT (JSON Web Token) Authentication:
a. JWT is commonly used in stateless applications. Spring Boot can be integrated
with JWT for token-based authentication, where the client receives a token
after logging in and uses it for subsequent requests.
For authorization, you control access to resources using roles or permissions. Spring
Security allows you to configure role-based access control (RBAC) using annotations like
@PreAuthorize or @Secured, or by configuring HTTP security rules to restrict access to
certain URLs based on the user’s roles or authorities.
@MockBean
private UserRepository userRepository;
Example:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
return new ResponseEntity<>(ex.getMessage(),
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Example:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.MyCustomAutoConfiguration
36. What is Spring Cloud and how does it integrate with Spring Boot?
Answer: Spring Cloud provides tools for microservice architecture, such as service
discovery (Eureka), circuit breakers (Hystrix), and configuration management (Config
Server).
37. How to use Spring Boot with Eureka for service discovery?
Answer: Add the spring-cloud-starter-netflix-eureka-client dependency and enable
service discovery with @EnableDiscoveryClient.
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
9: Miscellaneous
server.port=8443
server.ssl.key-store=classpath:keystore.jks
server.ssl.key-store-password=your-password
server.ssl.key-store-type=JKS
server.ssl.key-alias=your-alias
@Configuration
@EnableAsync
public class AsyncConfig {
}
Mark Method as Async: Use the @Async annotation on methods that should run
asynchronously:
@Service
public class MyService {
@Async
public CompletableFuture<String> processTask() {
// Simulate a long-running task
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return CompletableFuture.completedFuture("Task completed");
}
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
48. What is the default username and password when Spring Security is enabled?
Answer: The default username is user and the password is generated at startup and
logged to the console.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().loginPage("/login").permitAll();
}
@PreAuthorize("hasRole('ADMIN')")
public void someMethod() {
// Method implementation
}
51. What is JWT (JSON Web Token) and how does it work with Spring Boot?
Answer: JWT is a compact, URL-safe means of representing claims to be transferred
between two parties. It is often used for stateless authentication in REST APIs.
Example:
a. After successful login, a JWT token is generated and sent back to the client.
b. The client includes the token in the Authorization header for subsequent requests.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests().anyRequest().authenticated();
}
55. How can you integrate Spring Boot with LDAP for authentication?
Pavan Kumar | www.javadzone.com 22
Answer: Use the spring-boot-starter-ldap to authenticate users against an LDAP directory.
Example:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-ldap</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
58. How do you send and receive messages with RabbitMQ in Spring Boot?
Answer: Use @RabbitListener for consuming messages and RabbitTemplate for sending
messages.
Example:
@RabbitListener(queues = "queueName")
public void receiveMessage(String message) {
System.out.println("Received: " + message);
}
@Autowired
private RabbitTemplate rabbitTemplate;
Pavan Kumar | www.javadzone.com 23
public void sendMessage(String message) {
rabbitTemplate.convertAndSend("queueName", message);
}
Spring Kafka integrates Kafka's producer-consumer model into Spring Boot, simplifying
the configuration and usage of Kafka in your applications. It provides abstractions for both
producing messages to Kafka topics and consuming messages from Kafka topics.
Example:
<dependency>
<groupId>org.springframework.kafka</groupId>
artifactId>spring-kafka</artifactId>
</dependency>
60. How do you configure a Kafka producer and consumer in Spring Boot?
Answer: Configure Kafka properties in application.properties and define Kafka producer
and consumer beans.
Example:
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=test-group
@RestController
public class WebFluxController {
@GetMapping("/mono")
public Mono<String> getMono() {
return Mono.just("Hello, Reactive World!");
}
}
Spring Cloud integrates seamlessly with Spring Boot to help you develop scalable, resilient,
and easily manageable microservices applications.
68. How do you use Spring Cloud Eureka for service discovery?
Answer: Spring Cloud Eureka is used for service registration and discovery. You need to
add the spring-cloud-starter-netflix-eureka-client dependency and enable discovery with
@EnableDiscoveryClient.
Example:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
Spring Cloud Config can be used to access configurations from various sources like Git
repositories, local files, or a database.
Example:
70. How do you configure Spring Boot with Spring Cloud Config Server?
Answer: Set up a @EnableConfigServer on a Spring Boot application to act as the Config
Server, and point applications to it for configuration management.
Example:
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
71. What is Spring Cloud Gateway and how is it used with Spring Boot?
Answer: Spring Cloud Gateway is used to route requests to different services in a
microservices architecture, acting as an API gateway.
Example:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
72. How do you implement load balancing in Spring Boot with Spring Cloud?
Answer: Spring Cloud integrates with Ribbon (client-side load balancing) to distribute
requests among different service instances. Use @LoadBalanced annotation with
RestTemplate to enable load balancing.
Example:
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
Pavan Kumar | www.javadzone.com 27
}
@HystrixCommand(fallbackMethod = "fallback")
public String callService() {
return restTemplate.getForObject("http://myservice", String.class);
}
74. How does Spring Boot work with Docker in the cloud?
Answer: Spring Boot applications can be easily packaged into Docker containers for cloud
deployment, allowing them to run in isolated environments. This process involves
creating a Dockerfile to define how the application should be built and run inside a Docker
container. You can build the Docker image using build tools like Maven or Gradle.
You can specify which profile is active by setting the spring.profiles.active property in
your application.properties or application.yml file, or by passing it as a command-line
argument.
Example:
# application-prod.properties
server.port=8080
datasource.url=jdbc:mysql://prod-db-server:3306/prod_db
2. Activate a profile:
spring.profiles.active=dev
Spring Boot will load the appropriate configuration based on the active profile, allowing
you to easily switch between different environments. This makes it simple to manage
settings like database URLs, logging levels, and server ports based on the environment.
77. How to use Spring Boot with external services like Redis or MongoDB?
Answer: Use the relevant Spring Boot starters (spring-boot-starter-data-redis, spring-
boot-starter-data-mongodb) and configure the connection properties in
application.properties.
i. Change the packaging type to WAR: In your pom.xml, change the packaging type
from jar to war:
a. <packaging>war</packaging>
Example:
@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder
configure(SpringApplicationBuilder application) {
return application.sources(MyApplication.class);
}
}
iii. Add a web.xml file (optional): If your application needs a custom configuration for a
servlet container, you can add a web.xml file, but this is typically optional in Spring
Boot.
Once you've made these changes, you can build the WAR file using Maven or Gradle:
The resulting .war file can be deployed to a servlet container like Apache Tomcat. This
approach allows you to run the Spring Boot application on an external server, while still
leveraging Spring Boot’s configuration and other features.
Conclusion
Congratulations on completing the Spring Boot Interview Preparation Guide!
In this guide, we've explored everything from the basics of Spring Boot to advanced topics such
as security, messaging, reactive programming, and cloud integration. With this knowledge,
you're now well-equipped to tackle Spring Boot-related interview questions with confidence.
I encourage you to stay curious and continue exploring Spring Boot beyond this guide. Real
mastery comes with continuous learning and real-world application.
To continue your learning journey and stay updated with the latest Spring Boot trends, tutorials,
and discussions, join our WhatsApp channel: Click here to join
By joining, you’ll be part of a community where you can ask questions, share insights, and stay
updated on new resources that will help you excel in Spring Boot.
If you have any questions or need further assistance, feel free to reach out to me. You can also
visit my blog at www.javadzone.com for more Spring Boot tutorials and resources.