Top 50 spring boot interviews : Security

Top 10 Questions on Spring Boot Basics with Answers

This entry is part 1 of 5 in the series Top 50 Interview Questions and Answers on Spring Boot

Spring Boot is a tool for Java programmers to quickly build ready-to-use applications. It reduces the need for complex setup and includes built-in servers. Big companies like Netflix and Amazon use it because it’s fast and easy to work with. This guide has practice questions for job interviews, covering basic Spring, web programming (APIs), smaller independent services (microservices), automatic setup, server handling, monitoring, and fixing errors.

I categorized the top 50 questions in the below 5 mazor categories. I hope below question and answer will help you in upcoming interview Let’s celebrate and start.

Basics

Question 1. What is Spring Boot, and how is it different from the Spring Framework?

Answer:
Spring Boot is a framework designed to simplify the development of Spring-based applications. It reduces the need for boilerplate code and configurations by providing defaults and auto-configuration.

Key Differences from the Spring Framework:

CategorySpringSpring Boot
ConfigurationSpring Framework requires extensive XML or Java-based configurationSpring Boot uses auto-configuration and convention over configuration
Embedded ServerSpring Boot comes with embedded servers, so you can run applications directly. Spring Boot comes with embedded servers, so you can run applications directly.  
DependenciesSpring Framework requires manual dependency managementSpring Boot uses “starters” to simplify dependency management
Production-Ready FeaturesSpring Framework does not provide these out of the box. Spring Framework applications typically need an external server (e.g., Tomcat, Jetty). 
Spring Vs Spring Boot

Example:

Spring Framework:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="myBean" class="com.example.MyBean"/>
</beans>

Spring Boot:

@SpringBootApplication
public class MySpringBootApp {
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApp.class, args);
    }
}

Question 2. What are the advantages of using Spring Boot?

Answer:
Spring Boot offers several advantages that make it a popular choice for developing modern applications:

  1. Simplified Configuration:
    • Eliminates the need for complex XML or Java-based configurations.
    • Provides auto-configuration to set up applications with minimal effort.
  2. Embedded Servers:
    • Comes with embedded servers like Tomcat, Jetty, and Undertow.
    • Simplifies deployment as applications can run independently.
  3. Starter Dependencies:
    • Provides “starter” dependencies to include all required libraries for a specific functionality.
    • Reduces time spent on dependency management.
  4. Microservices Ready:
    • Ideal for creating microservices with built-in features for RESTful APIs, messaging, and service discovery.
  5. Production-Ready Features:
    • Includes monitoring, health checks, and metrics out of the box.
    • Supports tools like Spring Boot Actuator for operational management.
  6. Rapid Development:
    • Speeds up development with a convention-over-configuration approach.
    • Reduces boilerplate code.
  7. Cloud Integration:
    • Easily integrates with cloud platforms and supports cloud-native development.
  8. Community and Ecosystem:
    • Backed by a large community and rich ecosystem of plugins and tools.

Example:

A simple Spring Boot application:

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

With Spring Boot, this application starts an embedded Tomcat server and runs with minimal configuration.

Question 3. How do you create a Spring Boot application?

Creating a Spring Boot application is quite straightforward, especially with Spring Initializr. Here’s a breakdown of the process, covering both using Spring Initializr (the recommended approach) and manual setup:

Method 1: Using Spring Initializr (start.spring.io)

This is the fastest and easiest way to get started.

Step 1.) Go to Spring Initialize: Open your web browser and go to https://spring.io/

Step 2.) Configure your project:

  • Project: Choose either Maven or Gradle (Maven is more common for beginners).
  • Language: Select Java, Kotlin, or Groovy.
  • Spring Boot: Choose the latest stable version. 
  • Group: Your project’s group ID (e.g., com.example).
  • Artifact: Your project’s name (e.g., my-spring-boot-app).
  • Name: A more descriptive name (optional).
  • Description: A brief description of your project (optional).
  • Package Name: Your project’s package name (e.g., com.dg.example.myapp).
  • Packaging: Choose Jar (for executable JAR) or War (for deployment to a web server). 

Step 3.) Add Dependencies: In the “Dependencies” section, search for and add the necessary dependencies. For a simple web application, you’ll likely need:

Spring Web provides support for building web applications, including RESTful APIs.

Step 4.) Generate the Project: Click the “GENERATE” button. This will download a zip file containing a basic Spring Boot project.

Step 5.) Import into IDE: Extract the zip file and import the project into your IDE (IntelliJ IDEA, Eclipse, or Spring Tools Suite).

Step 6.) Run the Application: Once imported, you’ll find a main application class (e.g., MySpringBootAppApplication.java). Run this class as a Java application. If everything is set up correctly, you’ll see Spring Boot’s startup logs in the console.

Method 2: Manual Setup (Less Common, for Deeper Understanding)

This method is more involved but helps you understand the underlying structure.

Step 1.) Add Spring Boot Dependencies: Add the Spring Boot Starter Parent and the necessary dependencies to your pom.xml (Maven) or build.gradle (Gradle) file. 

Step 2.) Create a Project: Create a new Maven or Gradle project in your IDE.

Maven (pom.xml):

XML
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.1.2</version> <relativePath/> </parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

Gradle (build.gradle, Kotlin DSL):

plugins {
    id("org.springframework.boot") version "3.1.2" // Use the latest version
    id("io.spring.dependency-management") version "1.1.2"
    id("java")
}

group = "com.example"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_17

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
}

Step 3.) Create the Main Application Class: Create a Java class annotated with @SpringBootApplication:

package com.dg.example.myapp; // Replace with your package

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MySpringBootAppApplication {

    public static void main(String[] args) {
        SpringApplication.run(MySpringBootAppApplication.class, args);
    }

}

Step 4.) Run the Application: Run the main class.

Key Concepts:

  • @SpringBootApplication: This annotation combines @Configuration, @EnableAutoConfiguration, and @ComponentScan. It tells Spring to set up the application context.
  • Spring Initializr: A web-based tool that simplifies the creation of Spring Boot projects. 
  • Starters: Dependency descriptors that bundle commonly used dependencies.

I highly recommend using Spring Initializr for creating new Spring Boot projects. It simplifies the setup and ensures you have the correct dependencies. Let me know if you have any more questions! 

Question 4. What is the Spring Boot starter dependency?

In Spring Boot, a starter dependency is a convenient way to include all the necessary dependencies for a specific feature or technology into your project with a single entry in your pom.xml (for Maven) or build.gradle (for Gradle).

Key points about Spring Boot starter dependencies:
  • Simplify dependency management: Instead of manually adding numerous dependencies for a particular technology (e.g., Spring Data JPA, Spring Web), you include a single starter dependency.  
  • Opinionated defaults: Starters often come with sensible default configurations, reducing the amount of boilerplate code you need to write.  
  • Easy to use: Adding a starter is as simple as including one dependency in your project’s build file.  
  • Wide variety: Spring Boot offers a wide range of starters for various technologies, including web development, data access, messaging, security, and more. 

Example:

To use Spring Data JPA for database access, you would include the following dependency in your pom.xml:

XML

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

This single dependency will automatically bring in all the required dependencies for using Spring Data JPA, such as:

  • Spring Core
  • Spring Data Commons
  • Spring ORM
  • Hibernate  
  • Transaction management

Commonly used Spring Boot starters:

  • spring-boot-starter-web: For building web applications, including RESTful services.
  • spring-boot-starter-data-jpa: For using JPA and Hibernate for database access.
  • spring-boot-starter-security: For adding security features to your application.
  • spring-boot-starter-test: For testing Spring Boot applications.
  • spring-boot-starter-jdbc: For using JDBC for database access.
  • spring-boot-starter-data-redis: For using Redis as a data store

By using Spring Boot starters, you can significantly reduce the time and effort required to set up and configure your Spring Boot projects

Question 5. What is the purpose of the application.properties or application.yml file?

The application.properties or application.yml file in Spring Boot serves as the central location for externalizing your application’s configuration. It allows you to define various settings that control the behavior of your Spring Boot application without modifying the application code itself.  

Here’s a breakdown of its purpose:

  • Externalizes Configuration: By separating configuration from code, you can easily modify application behavior without recompiling or redeploying the application. This is beneficial for different deployments (development, test, production) where configurations might vary.  
  • Defines Application Settings: You can define various settings in this file, such as:
    • Database connection details (URL, username, password)  
    • Server port number  
    • Logging levels  
    • Security configurations (e.g., encryption keys)  
    • Bean configurations (enabling/disabling beans)
    • Any other custom configuration your application needs
  • Supports Different Formats: Spring Boot offers two options for configuring your application:
    • .properties: This is the traditional format for configuration files in Java. It uses a simple key=value syntax.
    • .yml (YAML): This is a human-readable and more flexible format, especially for managing complex configurations with nested structures. YAML is often preferred due to its readability.  

Properties file

//Port
server.port=8081
//Database Configuration
server.servlet.context-path=/myapp
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret

//Logging Levels
logging.level.org.springframework=DEBUG
logging.level.com.example=INFO
//Profile Management
spring.profiles.active=dev

yaml file

server:
  port: 8081
  servlet:
    context-path: /myapp

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: root
    password: secret
  profiles:
    active: dev

  • Environment-Specific Configurations: You can also create separate configuration files for different environments (e.g., application-dev.yml for development, application-prod.yml for production). Spring Boot automatically loads the appropriate configuration file based on the active profile during runtime.  
Benefits of using application.properties/yml files:
  • Flexibility: Easily modify configurations without changing code.  
  • Maintainability: Easier to manage and understand configuration separate from application logic.  
  • Environment Agnostic: Allows specific configurations for different environments.  
  • Separation of Concerns: Keeps application code clean and focused on core functionality.

Overall, the application.properties or application.yml file is a crucial component for managing your Spring Boot application’s configuration, promoting flexibility, maintainability, and ease of deployment.

Question 6. How do you configure a Spring Boot application?

Configuring a Spring Boot application involves setting up various properties and beans to define its behavior. You can configure the application using the following steps:

1.) Project Setup
  • Spring Initializr: The easiest way to start a Spring Boot project. Go to https://start.spring.io/, select your build tool (Maven or Gradle), add necessary dependencies (e.g., spring-boot-starter-web, spring-boot-starter-data-jpa), and generate the project.
  • Manual Setup: If you prefer manual setup, create a new project in your IDE and add the Spring Boot parent POM and dependencies to your pom.xml (Maven) or build.gradle (Gradle).
2.) Application Properties/YAML
  • Create Configuration Files: Create application.properties or application.yml in the src/main/resources folder. These files will hold your application’s configurations.

Example application.properties:

server.port=8080
spring.datasource.url=jdbc:postgresql://localhost:5432/mydatabase
spring.datasource.username=myuser
spring.datasource.password=mypassword
logging.level.root=INFO

Example application.yml:

server:
  port: 8080
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/mydatabase
    username: myuser
    password: mypassword
logging:
  level:
    root: INFO
3.) Accessing Configuration Properties

@Value Annotation: Inject configuration properties into your classes using the @Value annotation.

@Component
public class MyService {

    @Value("${server.port}")
    private int serverPort;

    // ...
}

@ConfigurationProperties: For more complex configurations, use the @ConfigurationProperties annotation to bind properties to a Java class.

@ConfigurationProperties(prefix = "my.app")
public class MyAppProperties {
    private String message;

    // Getters and setters
}
4.) Environment-Specific Configurations
  • Create Profile-Specific Files: Create files like application-dev.properties, application-prod.properties, or application-test.yml for different environments.
  • Activate Profiles: Activate the desired profile during application startup (e.g., using command-line arguments, environment variables, or Spring Boot’s spring.profiles.active property).
5.) Advanced Configuration
  • Spring Profiles: Define and activate different profiles to customize application behavior for various environments.
  • Command-Line Arguments: Pass configuration properties as command-line arguments when starting the application.
  • Environment Variables: Read configuration values from environment variables.
  • Spring Cloud Config: For more advanced configuration management, use Spring Cloud Config Server to centrally manage and distribute configurations.
Key Points:
  • Externalize Configuration: Keep your application code clean and maintainable by separating configuration from code.
  • Environment-Specific Configurations: Easily adapt your application to different environments (development, testing, production).
  • Choose the Right Format: Use .properties for simple configurations and .yml for more complex, hierarchical structures.

By following these steps and leveraging the flexibility of Spring Boot’s configuration mechanisms, you can effectively manage and customize your application’s behavior according to your specific needs.

Question 7. What is the Spring Boot Actuator, and why is it used?

Spring Boot Actuator is a sub-project of Spring Boot that provides a set of built-in production-ready features to help you monitor and manage your application. It includes several endpoints that allow you to interact with the application, gather metrics, check the health, and perform various management tasks.  

Key Features and Use Cases:
  • Health Checks: Assess the overall health of your application and its dependencies (e.g., databases, external services).  
  • Metrics: Gather performance metrics like request counts, response times, memory usage, and garbage collection statistics.  
  • Info Endpoint: Expose build information, Git commit details, and other application-specific information.
  • Environment Endpoint: Inspect the environment variables and configuration properties of your application.  
  • Shutdown Endpoint: Gracefully shut down the application.  
  • Log Levels: Dynamically change logging levels for different loggers.  
  • HTTP Trace: Analyze HTTP requests and responses.  
  • Data Export: Export metrics to external systems like Prometheus or Graphite.
Why Use Spring Boot Actuator?
  • Enhanced Observability: Gain deeper insights into your application’s behavior and performance.  
  • Improved Troubleshooting: Quickly identify and diagnose issues.  
  • Proactive Maintenance: Monitor key metrics and proactively address potential problems.  
  • Simplified Management: Easily manage and control your application’s lifecycle.  
  • Integration with Monitoring Tools: Seamlessly integrate with popular monitoring and alerting systems.  
Example Endpoints:
  • /actuator/health: Check the health status of your application and its dependencies.  
  • /actuator/metrics: Retrieve a list of available metrics.  
  • /actuator/metrics/http.server.requests: Get the number of HTTP requests handled by your application.
  • /actuator/info: Get build information and other application-specific details.  
  • /actuator/env: View the environment variables and configuration properties.
To use Spring Boot Actuator:
  • Add the Dependency: Include the spring-boot-starter-actuator dependency in your pom.xml (Maven) or build.gradle (Gradle).
  • Enable Endpoints: By default, all endpoints are disabled. You can enable specific endpoints or all of them in your application.properties or application.yml file.
  • Access Endpoints: Access the endpoints through HTTP requests (e.g., using a web browser or tools like cURL).  

By leveraging Spring Boot Actuator, you can significantly enhance the monitoring, management, and troubleshooting capabilities of your Spring Boot applications.

Question 8. How does Spring Boot auto-configuration work?

Spring Boot’s auto-configuration feature simplifies application setup by automatically configuring beans and settings based on the dependencies present in the classpath. It uses the “convention over configuration” principle to minimize the need for manual configuration.

How It Works:
  • Dependency Detection: Spring Boot scans the classpath for specific libraries or frameworks (e.g., spring-boot-starter-data-jpa, spring-boot-starter-web).
  • Enable Auto-Configuration: The @SpringBootApplication annotation includes @EnableAutoConfiguration, which activates the auto-configuration process.
  • Conditional Configuration: Spring Boot uses @Conditional annotations to apply configurations only when certain conditions are met (e.g., a class or property exists).
  • Default Beans: Provides default bean configurations, which can be overridden if custom configurations are provided.
Example:
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
Customizing Auto-Configuration:

You can exclude specific auto-configurations using the exclude attribute:

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
Benefits of Auto-Configuration:
  • Reduces boilerplate code.
  • Speeds up development.
  • Simplifies integration with third-party libraries.
  • Auto-configuration makes Spring Boot applications easy to set up and minimizes manual configuration efforts.

Question 9. How do you disable specific auto-configuration classes in Spring Boot?

you can disable specific auto-configuration classes in Spring Boot using the @EnableAutoConfiguration(exclude = { … }) annotation.

Here’s how it works:

Import @EnableAutoConfiguration: If you’re using the @SpringBootApplication annotation, it already implicitly imports @EnableAutoConfiguration.

Specify Excluded Classes: Within the @EnableAutoConfiguration annotation, use the exclude attribute to specify the fully qualified names of the auto-configuration classes you want to disable.

Example:

@SpringBootApplication(exclude = {
        DataSourceAutoConfiguration.class, 
        HibernateJpaAutoConfiguration.class 
})
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

DataSourceAutoConfiguration and HibernateJpaAutoConfiguration are disabled, meaning Spring Boot will not automatically configure a data source or JPA for your application.

Alternative Approaches:

Conditional on Property: You can use @ConditionalOnProperty to conditionally enable or disable auto-configuration based on a property value.

Custom Auto-Configuration: Create your own custom auto-configuration classes that override or replace the default ones.

Important Notes:

Disabling auto-configuration can sometimes lead to unexpected behavior if you rely on the default configurations.
Always carefully consider the implications of disabling auto-configuration classes before making changes.
By using these methods, you can fine-tune the auto-configuration behavior of your Spring Boot application and tailor it to your specific needs.

Question 10. What is the Spring Initializr?

Spring Initializr is a web-based tool that simplifies the creation of new Spring Boot projects.

Spring initializr by https://spring.io/
Purpose:
  • Project Scaffolding: It generates the basic project structure, including necessary files and directories.
  • Dependency Management: It automatically includes the required Spring Boot starter dependencies based on your project’s needs.  
  • Configuration: It allows you to customize various project settings, such as build system (Maven or Gradle), language (Java, Kotlin, Groovy), and Spring Boot version.  
Key Features:
  • Web Interface: User-friendly interface for selecting project options.  
  • Dependency Selection: Choose from a wide range of Spring Boot starters for web, data, security, and more.  
  • Project Generation: Generates a ready-to-use project archive (ZIP or .jar) that you can import into your IDE.  
  • Customization Options: Configure various project settings like language, build system, and packaging.  
  • Integration with IDEs: Many IDEs have plugins that integrate directly with Spring Initializr, providing a seamless experience.  
Benefits:
  • Faster Development: Significantly reduces the time and effort required to set up a new Spring Boot project.
  • Reduced Errors: Minimizes the risk of misconfiguring dependencies or project structure.
  • Improved Productivity: Focus on application development rather than project setup.  

In essence, Spring Initializr streamlines the initial stages of Spring Boot development, making it easier and faster for developers to get started with new projects.

To know more about spring boot, refer to this article: Spring Boot.

Series NavigationTop 10 Questions on Spring Boot Annotations with Answers >>

Leave a Reply

Your email address will not be published. Required fields are marked *