Friday, March 21, 2025

Spring Boot Interview Questions and Answers

  • What is SpringBoot ? How it is different from Spring framework ?
Spring Boot is an extension of the Spring Framework that simplifies the development of Java applications by providing auto-configuration, an embedded server, and opinionated defaults.

BasisSpringSpring Boot
Where it’s used?Spring framework is a java EE framework that is used to build applications.Spring Boot framework is mainly used to develop REST API’s
Key featureThe primary or most important feature of the Spring framework is dependency injection(Dependency Injection (DI) is a design technique that removes dependencies from computer code, making the application easier to maintain and test).The main or primary feature of the Spring Boot is Autoconfiguration( Simply described, Spring Boot autoconfiguration is a method of automatically configuring a Spring application based on the dependencies found on the classpath.)
Autoconfiguration can speed up and simplify development by removing the need to define some beans that are part of the auto-configuration classes.
Why it’s usedIts goal is to make Java EE (Enterprise Edition) development easier, allowing developers to be more productive.Spring Boot provides the RAD(Rapid Application Development) feature to the Spring framework for faster application development.
Type of Application DevelopmentSpring framework helps to create a loosely coupled application.Spring Boot helps to create a stand-alone application.
Servers dependencyIn the Spring framework to test the Spring Project, we need to set up the servers explicitly.Spring Boot offers built-in or embedded servers such as Tomcat and jetty.


In-memory database supportSpring framework does not provide support for the in-memory database.Spring Boot provides support for the in-memory database such as H2.
Boilerplate codeSpring framework requires too many lines of code (boilerplate code) even for minimal tasks.You avoid boilerplate code which reduces time and increases productivity.
ConfigurationsIn the Spring framework, you have to build configurations manually.In Spring Boot there are default configurations that allow faster bootstrapping.
DependenciesSpring Framework requires a number of dependencies to create a web app.Spring Boot, on the other hand, can get an application working with just one dependency. There are several more dependencies required during build time that is added to the final archive by default.

TestingTesting in Spring Boot is difficult in comparison to Spring Boot due to a large amount of source code.Testing in Spring Boot is easier due to the reduced amount of source code.
XML ConfigurationIn the Spring framework, XML Configuration is required.No need for XML configuration in Spring Boot.
CLI ToolsSpring framework does not provide any CLI tool for developing and testing applications.Spring Boot provides a CLI tool for developing and testing Spring Boot applications.
PluginsSpring framework does not provide any plugin for maven, Gradle, etc. like Spring Boot.Spring Boot provides build tool plugins for Maven and Gradle. The Plugins offer a variety of features, including the packaging of executable jars.
  • What is the purpose of SpringBootApplication Annotation?
@SpringBootApplication comprises of @EnableAutoConfiguration, @ComponentScan and @Configuration. Its typically used to mark the main class of Spring Boot application. It enables Spring Boot's auto-configuration mechanism, which automatically configures the Spring application based on its dependencies and the content of the classpath.
  • What are Spring Boot starters?
Spring Boot starters are pre-configured dependency bundles that simplify adding dependencies to a project. They help developers avoid manually specifying multiple dependencies by providing a single starter dependency for common use cases.
  • What is Spring Boot Actuator ?
Spring Boot Actuator is a module that provides production-ready features to monitor and manage Spring Boot applications. It exposes various endpoints to gather metrics, health status, application info, logs etc. To enable the spring actuator feature, we need to add the dependency of “spring-boot-starter-actuator” in pom.xml.
<dependency>
<groupId> org.springframework.boot</groupId>
<artifactId> spring-boot-starter-actuator </artifactId>
</dependency>
  • Difference between @Primary and @Qualifier annotation?
In Spring Framework, @Primary and @Qualifier are used for resolving bean conflicts when multiple beans of the same type are available in the Application Context.
  1. @Primary - Used to mark a bean as the default choice when the multiple beans of the same type exists. Applied at the class level on a bean definition. Works when there is no explicit @Qualifier used in injection.
  2. @Qualifier - Used to specify the exact bean to be injected when multiple candidates exists. Ovverides @Primary if both are present. Applied at the injection point (constructor, method or field)
  • What is Dependency Injection ?
Dependency Injection (DI) is a design pattern used to manage dependencies between objects by injecting them rather than creating them inside a class. It helps in building loosely coupled, testable and maintainable applications.
  • Explain bean scopes in Spring Boot ?
In Spring Boot, a bean scope defines how and when a Spring bean is created and shared within the Spring IoC(Inversion of Control) container. Spring provides different bean scopes for different use cases.
  1. Singleton: The default scope, where only one instance of a bean is created for the entire                           application.
  2. Prototype: A new instance is created for each time the bean is requested.
  3. Request : A new instance is created for each HTTP request.
  4. Session: A new instance is created for each user session.
  5. Application: A new instance is created once for the entire application.
  6. WebSocket: A new instance is created for each WebSocket session.
  • Explain @Autowired annotation?
The @Autowired annotation in Spring Boot is used for automatic dependency injection. It tells Spring to inject a bean automatically without manually creating an instance.
  • What is IoC Container?
Inversion of Control (IoC) is a design principle where the control of object creation and dependency management is shifted from the application code to a framework or container. In Spring Boot, this is managed by the Spring IoC Container. 
Instead of manually creating objects, Spring Boot automatically created and injects dependencies where needed.
IoC Container is responsible for:
  1. Creating and managing beans (objects in Spring).
  2. Injecting dependencies into beans (@Autowired)
  3. Handling bean lifecycle (initialization and destruction).
  •  What are profiles in Spring boot ?
In Spring Boot, profiles are a way to define and manage different configurations for different environments (e.g., development, testing, production). They allow you to separate configuration 
settings that might change depending on the environment where the application is running. 
Profiles can be defined in two main ways:
  1. Application properties: You can specify profiles in the application.properties or application.yml files.
  2. Java code: You can use the @Profile annotation to specify beans that should only be loaded under certain profiles.
Example: Using @Profile Annotation in Java Classes

You can use the @Profile annotation in Spring beans to specify that a bean is only available for certain profiles:

@Configuration @Profile("dev") public class DevConfig { @Bean public MyService devService() { return new DevServiceImpl(); } } @Configuration @Profile("prod") public class ProdConfig { @Bean public MyService prodService() { return new ProdServiceImpl(); } }
  • Difference between BeanFactory and ApplicationContext ?
BeanFactory & ApplicationContext are different types of "Spring Container" which are used for managing beans in a Spring application. BeanFactory is simpler and lightweight, ideal for basic small, standalone applications. ApplicationContext is more powerful and feature-rich, supporting a wider range of functionalities for enterprise-level applications.

Below are some differences between BeanFactory & ApplicationContext :-

AspectBeanFactoryApplicationContext
1. DefinitionIt is "basic container" that manages beans with minimal features.Its is "advanced container" extending BeanFactory with extra features.
2. UsageIt is suitable for small, standalone applications.It is suitable for web applications, AOP, ORM and large enterprise applications.
3. Resource UsageIt requires less memory, suitable for lightweight or memory-critical applications.It uses more memory, providing additional features for enterprise applications.
4. InitializationIt uses lazy initialization i.e. it creates the beans only when needed.It uses eager initialization i.e. it loads and creates the beans at container startup.
5. Bean Scopes SupportedIt supports only Singleton and Prototype scopes.It supports all scopes, including Request and Session, for web contexts.
6. Annotation SupportIt doesn’t support annotations; requires XML configuration.It supports annotations for simpler configuration.
7. InternationalizationIt does not provide support for internationalization (i18n).It provides the i18n support for multilingual applications.
8. Event HandlingIt does not support event handling.It supports event handling via ApplicationEvent and ApplicationListener.
9. Bean Post ProcessingIt requires manual registration of BeanPostProcessor and BeanFactoryPostProcessor.It automatically registers BeanPostProcessor and BeanFactoryPostProcessor at startup.
  • What does @ComponentScan annotation do ?
The @ComponentScan annotation in Spring is used to specify the base packages to scan for Spring beans. It tells Spring to look in certain packages for classes annotated with @Component, @Service, @Repository, @Controller, or other stereotype annotations, and then automatically register those classes as Spring beans in the application context.
You typically use @ComponentScan in a configuration class annotated with @Configuration, though it's also commonly used in combination with @SpringBootApplication in Spring Boot applications (since @SpringBootApplication includes @ComponentScan by default).
Here’s a basic example:
@Configuration @ComponentScan(basePackages = "com.example.myapp") public class AppConfig { }
  • How to connect Spring Boot with a database?
Configuring a Spring Boot application to connect to a database is a common task, and Spring Boot provides built-in support for various databases (like MySQL, PostgreSQL, H2, etc.) through the use of Spring Data JPA and Spring JDBC. Here's a step-by-step guide on how to configure Spring Boot with a relational database.

Step 1 - Add Dependencies : Spring Boot makes it easy to connect to databases by including the necessary dependencies in your pom.xml (for Maven) or build.gradle (for Gradle).

For Maven:
If you're using Spring Data JPA and a relational database like MySQL or PostgreSQL, add the following dependencies to your pom.xml:
<dependencies> <!-- Spring Boot Starter Web (optional, if you need a web application) --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Boot Starter Data JPA (for JPA integration) --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- Database Driver (e.g., MySQL) --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- H2 Database for in-memory testing (optional) --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> </dependencies>
For Gradle:
If you're using Gradle, you can add these dependencies in build.gradle:
dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'mysql:mysql-connector-java' runtimeOnly 'com.h2database:h2' // For in-memory database }
Step 2 - Configure application.properties or application.yml
You need to define the database connection properties in application.properties or application.yml.
Example for application.properties (for MySQL):
# DataSource Configuration spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=rootpassword spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # Hibernate Configuration (JPA) spring.jpa.hibernate.ddl-auto=update # Use 'create', 'create-drop', or 'none' for different behaviors spring.jpa.show-sql=true # Show SQL queries in the console (for debugging) spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect # Enable or Disable SQL Formatting (optional) spring.jpa.properties.hibernate.format_sql=true

No comments:

Post a Comment