Hide/Show table of contents
-
Spring Boot is an open-source framework built on top of the Spring Framework that simplifies the development of Java-based applications. It is designed to make it easier to create stand-alone, production-grade Spring-based applications with minimal configuration.
-
The main advantages of Spring Boot include:
- Auto-configuration: Automatically configures Spring and third-party libraries based on project dependencies.
- Standalone: Spring Boot applications can run as standalone Java applications.
- Production-ready: Includes features like metrics, health checks, and externalized configuration.
- Microservice-ready: Ideal for building microservices due to its lightweight and modular design.
-
Major features of Spring Boot are:
- Auto-configuration: Automatically configures your Spring application based on the dependencies you have added.
- Standalone: Spring Boot applications can be run from the command line.
- Production-ready: Includes built-in features for monitoring and managing your application.
- Microservices: Facilitates building microservices with minimal configuration.
-
- Configuration: Spring requires extensive XML configuration or Java-based configuration. Spring Boot offers auto-configuration and minimal setup.
- Setup: Spring projects typically need manual setup and configuration, while Spring Boot provides default configurations and embedded servers.
- Dependencies: Spring Boot includes a variety of dependencies and auto-configuration out of the box, reducing the need for manual dependency management.
-
Spring Boot simplifies development by:
- Reducing Configuration: Provides default configurations and auto-configuration options.
- Embedded Servers: Includes embedded servers like Tomcat, Jetty, or Undertow, eliminating the need for external server setup.
- Spring Boot Starter Projects: Offers pre-configured dependency sets for common tasks.
-
To create a Spring Boot application using Maven, follow these steps:
-
Add the Spring Boot dependencies to your
pom.xml
:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency>
-
Create the main application class with
@SpringBootApplication
annotation:import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
-
Run your application using Maven:
mvn spring-boot:run
-
-
To create a Spring Boot project using Spring Initializr:
- Visit Spring Initializr.
- Choose the project metadata (e.g., Project, Language, Spring Boot version).
- Add dependencies.
- Click "Generate" to download a ZIP file containing your Spring Boot project.
-
To create a simple Spring Boot application:
-
Create a new Maven project and add Spring Boot dependencies.
-
Create a main application class with
@SpringBootApplication
.import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
-
Create a REST controller:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class HelloController { @GetMapping("/hello") public String sayHello() { return "Hello, Spring Boot!"; } }
-
-
Spring Boot Starters are a set of convenient dependency descriptors you can include in your application. They simplify the process of adding commonly used dependencies.
Example of including a Spring Boot Starter in
pom.xml
:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
-
The
@SpringBootApplication
annotation is used to mark the main class of a Spring Boot application. It combines the following annotations:@Configuration
@EnableAutoConfiguration
@ComponentScan
It enables auto-configuration and component scanning.
-
The Spring Initializr is an online tool that helps generate a Spring Boot project with the desired configuration and dependencies. You can access it at start.spring.io.
-
Key Spring Boot annotations include:
@SpringBootApplication
@RestController
@RequestMapping
@Service
@Repository
@Configuration
-
Spring Boot manages dependencies by providing default versions and configurations for commonly used libraries through its starter dependencies. It helps avoid version conflicts and simplifies dependency management.
-
Spring Boot properties are configuration settings that can be defined in
application.properties
orapplication.yml
files to customize the behavior of your application.Example of
application.properties
:server.port=8081 spring.datasource.url=jdbc:mysql://localhost:3306/mydb
-
Spring Boot starters are pre-configured dependency sets for common application needs. They simplify dependency management by grouping related dependencies into a single artifact.
-
Spring Boot Actuator provides production-ready features such as monitoring, metrics, and health checks. It helps in managing and monitoring your application in production environments.
-
To connect Spring Boot to a database using JPA:
-
Add JPA and database dependencies to
pom.xml
:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency>
-
Configure database settings in
application.properties
:spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
-
Create JPA entity and repository:
@Entity public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; // Getters and setters } public interface UserRepository extends JpaRepository<User, Long> {}
-
-
To connect Spring Boot to a database using JDBC:
-
Add JDBC dependency to
pom.xml
:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
-
Configure database settings in
application.properties
:spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=root
-
Create a
JdbcTemplate
bean:import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; @Configuration public class DataSourceConfig { @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } }
-
-
The
@RestController
annotation is a combination of@Controller
and@ResponseBody
. It is used to create RESTful web services by marking a class as a web controller where every method returns a domain object instead of a view.Example:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class HelloController { @GetMapping("/hello") public String sayHello() { return "Hello, Spring Boot!"; } }
-
The
@RequestMapping
annotation is used to map web requests to specific handler methods. It can be used at the class or method level to define the URL patterns for which the methods should be invoked.Example:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class HelloController { @GetMapping("/hello") public String sayHello() { return "Hello, Spring Boot!"; } }
-
Spring Boot simplifies dependency management by:
- Providing Starters: Pre-configured dependency sets for common use cases.
- Auto-Configuration: Automatically configures application components based on the included dependencies.
- Dependency Management: Uses dependency management to handle version conflicts and ensure compatibility.
-
Embedded servers in Spring Boot allow applications to be run as standalone Java applications. Spring Boot includes embedded servers like Tomcat, Jetty, and Undertow, which simplifies deployment and reduces the need for external web server setup.
-
Profiles in Spring Boot are used to segregate parts of your application configuration and make it only available in certain environments. They help in managing different configurations for development, testing, and production.
Example of using profiles:
# application-dev.properties server.port=8081 # application-prod.properties server.port=80
-
Basic Spring Boot annotations include:
@SpringBootApplication
@RestController
@Service
@Repository
@Configuration
@Component
-
Yes, you can change the port of the embedded Tomcat server by setting the
server.port
property inapplication.properties
:server.port=8081
-
A Spring Boot starter is a dependency descriptor that simplifies adding common dependencies. For example,
spring-boot-starter-web
is used for building web applications:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
-
The default port of Tomcat in Spring Boot is
8080
. You can change it by setting theserver.port
property inapplication.properties
:server.port=8081
-
Yes, you can disable the default web server in a Spring Boot application by using the
spring.main.web-application-type
property. Set it tonone
:spring.main.web-application-type=none
-
You can exclude a specific auto-configuration class by using the
@SpringBootApplication
annotation with theexclude
attribute:@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
-
Yes, you can create a non-web application in Spring Boot by setting the
spring.main.web-application-type
property tonone
inapplication.properties
:spring.main.web-application-type=none
-
The
@RestController
annotation combines@Controller
and@ResponseBody
. It is used to create RESTful web services where each method returns a domain object instead of a view. The response is serialized directly to JSON or XML.Example:
@RestController @RequestMapping("/api") public class HelloController { @GetMapping("/hello") public String sayHello() { return "Hello, Spring Boot!"; } }
-
@Controller
: Used for creating web controllers that return views (HTML, JSP). Methods typically return the name of a view to be rendered.@RestController
: Used for creating RESTful web services. Methods return domain objects, and the response is serialized to JSON or XML.
-
@RequestMapping
: Can be used to map HTTP requests to specific handler methods, supporting all HTTP methods (GET, POST, PUT, DELETE, etc.).@GetMapping
: A specialized version of@RequestMapping
for handling GET requests.
Example:
@RequestMapping("/api") public class MyController { @GetMapping("/hello") public String hello() { return "Hello!"; } @PostMapping("/hello") public String createHello() { return "Created!"; } }
-
Profiles in Spring Boot allow you to segregate application configuration and make it available only in specific environments. You can define different properties for different profiles (e.g.,
dev
,test
,prod
).Example:
# application-dev.properties server.port=8081 # application-prod.properties server.port=80
To activate a profile, use:
spring.profiles.active=dev
-
To enable Actuator, add the
spring-boot-starter-actuator
dependency to yourpom.xml
:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
You can then access actuator endpoints such as
/actuator/health
and/actuator/info
. -
You can handle exceptions using
@ControllerAdvice
and@ExceptionHandler
annotations:@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<String> handleException(Exception ex) { return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } }
-
Swagger is a tool used to document and test RESTful APIs. In Spring Boot, you can integrate Swagger using the
springfox-swagger2
andspringfox-swagger-ui
dependencies.Example configuration:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
-
To implement security, add the
spring-boot-starter-security
dependency. Then, configure security settings using@Configuration
and@EnableWebSecurity
:@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin(); } }
-
Spring Boot applications can be configured using:
application.properties
orapplication.yml
files- Command-line arguments
- Environment variables
- Java configuration classes with
@Configuration
and@Bean
-
Spring Data JPA is a part of the Spring Data project that simplifies database access and integrates JPA with Spring. Hibernate is a JPA implementation. Spring Data JPA provides additional functionality like repositories and query methods to ease data access.
-
To use Spring Boot with Docker, create a
Dockerfile
:FROM openjdk:17-jdk COPY target/myapp.jar /myapp.jar ENTRYPOINT ["java", "-jar", "/myapp.jar"]
Build and run the Docker image:
docker build -t myapp . docker run -p 8080:8080 myapp
-
@Component
: Generic stereotype for any Spring-managed component.@Service
: Specialized form of@Component
, typically used for service-layer beans.@Repository
: Specialized form of@Component
, used for data access layer beans with additional exception translation capabilities.
-
You can test RESTful services using
@WebMvcTest
or@SpringBootTest
with tools likeMockMvc
:@WebMvcTest(HelloController.class) public class HelloControllerTest { @Autowired private MockMvc mockMvc; @Test public void testHello() throws Exception { mockMvc.perform(get("/api/hello")) .andExpect(status().isOk()) .andExpect(content().string("Hello, Spring Boot!")); } }
-
To configure multiple data sources, define multiple
DataSource
beans and use@Primary
to indicate the default one:@Configuration public class DataSourceConfig { @Bean @Primary @ConfigurationProperties("spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean @ConfigurationProperties("spring.datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } }
-
The
@Autowired
annotation is used for dependency injection. It allows Spring to automatically inject the required dependencies into a bean. -
You can handle CORS by configuring it globally or at the controller level. For global configuration:
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:3000") .allowedMethods("GET", "POST", "PUT", "DELETE"); } }
-
To create an Interceptor, use the
@Component
annotation to define it as a Spring bean and implement theHandlerInterceptor
interface:@Component public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // Logic before the request is handled return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // Logic after the request is handled } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // Logic after the request completes } }
Register the interceptor with Spring:
@Configuration public class WebConfig implements WebMvcConfigurer { @Autowired private MyInterceptor myInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor); } }
-
Swagger is used to document and test RESTful APIs. It generates interactive API documentation and provides a user interface for testing endpoints.
To integrate Swagger, add the following dependencies:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
Configure Swagger:
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } }
Access the Swagger UI at
/swagger-ui.html
. -
- Spring Data JPA: A part of Spring that simplifies data access and integrates JPA with Spring. It provides a repository abstraction and various query methods.
- Hibernate: A JPA implementation that provides ORM capabilities for mapping Java objects to database tables. Spring Data JPA can use Hibernate as the JPA provider.
-
To use Spring Boot with Docker, create a
Dockerfile
in the root of your project:FROM openjdk:17-jdk COPY target/myapp.jar /myapp.jar ENTRYPOINT ["java", "-jar", "/myapp.jar"]
Build and run the Docker image:
docker build -t myapp . docker run -p 8080:8080 myapp
-
To implement caching, add the
spring-boot-starter-cache
dependency and enable caching with@EnableCaching
:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
@Configuration @EnableCaching public class CacheConfig { }
Use the
@Cacheable
annotation to cache method results:@Service public class MyService { @Cacheable("myCache") public String getCachedValue(String key) { // Method logic } }
-
Enable asynchronous processing with
@EnableAsync
and use@Async
for asynchronous methods:@Configuration @EnableAsync public class AsyncConfig { }
@Service public class MyService { @Async public CompletableFuture<String> asyncMethod() { // Asynchronous logic return CompletableFuture.completedFuture("result"); } }
-
Define multiple
DataSource
beans in a configuration class:@Configuration public class DataSourceConfig { @Bean @Primary @ConfigurationProperties("spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean @ConfigurationProperties("spring.datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } }
-
The
@ComponentScan
annotation is used to specify the packages to scan for Spring components, such as@Component
,@Service
,@Repository
, and@Controller
.@Configuration @ComponentScan(basePackages = "com.example.myapp") public class AppConfig { }
-
Spring Boot Actuator provides monitoring endpoints. Enable it by adding the
spring-boot-starter-actuator
dependency:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
Access endpoints like
/actuator/health
and/actuator/metrics
to monitor the application. -
Add dependencies for OpenTelemetry and configure it:
<dependency> <groupId>io.opentelemetry</groupId> <artifactId>opentelemetry-sdk-extension-autoconfigure-spring-boot</artifactId> <version>1.7.2</version> </dependency>
Configure OpenTelemetry in
application.properties
:otel.exporter.otlp.endpoint=http://localhost:4317
Use the OpenTelemetry API to instrument your code.
-
To enable HTTPS, configure SSL in
application.properties
:server.port=8443 server.ssl.key-store=classpath:keystore.p12 server.ssl.key-store-password=password server.ssl.key-store-type=PKCS12
Place the
keystore.p12
file insrc/main/resources
. -
Spring Boot WebFlux is a reactive web framework that supports non-blocking and asynchronous processing. It is an alternative to the traditional Spring MVC framework for building reactive applications.
-
Reactive programming is a paradigm that deals with asynchronous data streams and the propagation of changes. Spring Boot supports reactive programming with the Reactor framework.
-
To deploy as a WAR file, modify
pom.xml
to package the application as a WAR:<packaging>war</packaging>
Extend
SpringBootServletInitializer
in your main application class:@SpringBootApplication public class MyApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(MyApplication.class); } public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
Build the WAR file with:
mvn clean package
-
Add the
spring-boot-starter-amqp
dependency:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
Configure RabbitMQ settings in
application.properties
:spring.rabbitmq.host=localhost spring.rabbitmq.port=5672
Define a message listener:
@Component public class MyMessageListener { @RabbitListener(queues = "myQueue") public void receiveMessage(String message) { System.out.println("Received: " + message); } }
-
Configure the data source in
application.properties
:spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=password
-
Create a Docker image of your Spring Boot application and deploy it on Kubernetes using a YAML configuration file. Define a deployment and service in
deployment.yaml
:apiVersion: apps/v1 kind: Deployment metadata: name: myapp spec: replicas: 1 selector: matchLabels: app: myapp template: metadata: labels: app: myapp spec: containers: - name: myapp image: myapp:latest ports: - containerPort: 8080 --- apiVersion: v1 kind: Service metadata: name: myapp-service spec: ports: - port: 80 targetPort: 8080 selector: app: myapp
Apply the configuration with:
kubectl apply -f deployment.yaml
-
Add the
spring-boot-starter-oauth2-client
dependency:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency>
Configure OAuth2 client settings in
application.properties
:spring.security.oauth2.client.registration.google.client-id=your-client-id spring.security.oauth2.client.registration.google.client-secret=your-client-secret
The questions provided in this repository are the summary of frequently asked questions across numerous companies. We cannot guarantee that these questions will actually be asked during your interview process, nor should you focus on memorizing all of them. The primary purpose is for you to get a sense of what some companies might ask — do not get discouraged if you don't know the answer to all of them — that is ok!
Good luck with your interview 😊