Spring and Spring Boot Interview Questions


Q1. What is Dependency Injection? 




Q2. Why is Dependency Injection Important?




Q3. How can you implement Dependency Injection in Spring?


In Spring, Dependency Injection (DI) can be implemented in three different ways:



Each approach has its own advantages and trade-offs, and the choice of which to use depends on the design and structure of your application. Let's dive into each of them in detail.


Constructor Injection


Constructor Injection is when dependencies are provided to a class through its constructor. Spring resolves and injects the necessary dependencies when it creates the bean.


How it Works:



Example:


@Component

public class UserService {


    private final UserRepository userRepository;


    // Constructor Injection

    @Autowired

    public UserService(UserRepository userRepository) {

        this.userRepository = userRepository;

    }


    public void performService() {

        // logic

    }

}


In this case:


Advantages of Constructor Injection:



Disadvantages:



Setter Injection


Setter Injection involves injecting dependencies into a class using setter methods. Spring calls the setter methods after the object is created to inject the dependencies.


How it Works:



Example:


@Component

public class UserService {


    private UserRepository userRepository;


    // Setter Injection

    @Autowired

    public void setUserRepository(UserRepository userRepository) {

        this.userRepository = userRepository;

    }


    public void performService() {

        // logic

    }

}


In this case:


Advantages of Setter Injection:



Disadvantages:



Field Injection


Field Injection is when Spring directly injects dependencies into a class’s fields (member variables) without using constructors or setters. This is done using the @Autowired annotation directly on the field.


How it Works:



Example:


@Component

public class UserService {


    @Autowired

    private UserRepository userRepository;


    public void performService() {

        // logic

    }

}


In this case:


Advantages of Field Injection:



Disadvantages:



Best Practices and When to Use Each Approach



Conclusion



In modern Spring development, Constructor Injection is the preferred approach due to its clarity, immutability, and ease of testing.



Q4. What are Beans?


Definition: A bean is an object managed by the Spring IoC (Inversion of Control) container. Spring beans are defined and instantiated by the container and injected into dependent objects. These beans form the backbone of a Spring application, representing the components that get instantiated, configured, and assembled by the container at runtime. Beans are typically defined using annotations or in XML configuration, and Spring manages their life cycle, from creation to destruction.



Q5. How Do You Define a Bean in Spring?


There are several ways to define a bean in Spring:



A method annotated with @Bean inside a class marked with @Configuration defines a Spring bean.


Example:

@Configuration

public class AppConfig {


    @Bean

    public UserService userService() {

        return new UserService();

    }

}


Here, userService() defines a bean named userService of type UserService. The Spring container will manage the life cycle of this object.



Another way to define a bean is by annotating a class with @Component, which automatically registers it as a Spring bean.

Example:

@Component

public class UserService {

    // business logic

}


When you annotate a class with @Component, Spring will automatically detect and register this class as a bean if component scanning is enabled using @ComponentScan.



In addition to @Component, other annotations like @Service, @Repository, and @Controller are specializations of @Component and are used to denote specific roles in the application:



Q6. What are the different scopes available for beans? 


Bean Scopes in Spring defines the life cycle and visibility of the bean. 


There are five scopes in Spring, with two being the most commonly used (singleton and prototype).



Example:


@Bean

@Scope("singleton") // Optional, as "singleton" is the default

public UserService userService() {

    return new UserService();

}



Example:

@Bean

@Scope("prototype")

public UserService userService() {

    return new UserService();

}



Example:

@Bean

@Scope("request")

public UserService userService() {

     return new UserService();

}



Example:

@Bean

@Scope("session")

public UserService userService() {

    return new UserService();

}



Example:

@Bean

@Scope("application")

public UserService userService() {

    return new UserService();

}



Q7. How Does Spring Manage Bean Life Cycle?




Q8. What are Annotations? 




Q9. Can you explain some commonly used annotations in Spring and their purposes? 




Q10. What is the difference between Spring and Spring Boot? 




Q11. How does Spring Boot simplify application development compared to Spring? 


Spring Boot simplifies application development significantly compared to the traditional Spring Framework by providing a suite of tools, pre-configurations, and conventions that minimize the need for manual setup. Here's a detailed look at how Spring Boot simplifies things:

1. Opinionated Defaults and Auto-Configuration


@SpringBootApplication

public class MyApplication {

    public static void main(String[] args) {

        SpringApplication.run(MyApplication.class, args);

    }

}

2. Embedded Web Server

Embedded Tomcat/Jetty/Undertow: Spring Boot comes with an embedded Tomcat by default, but you can switch to Jetty or Undertow if needed. This means no need for external web servers.

java -jar myapp.jar

3. Reduced Boilerplate Code


<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-web</artifactId>

</dependency>

4. No XML Configuration Required

public class MyApp {

    public static void main(String[] args) {

        SpringApplication.run(MyApp.class, args);

    }

}

5. Production-Ready Features


<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

6. Opinionated Development Practices


# application-dev.properties

spring.datasource.url=jdbc:mysql://localhost:3306/devdb

spring.datasource.username=dev_user

spring.datasource.password=dev_pass


# application-prod.properties

spring.datasource.url=jdbc:mysql://prod-db-server:3306/proddb

spring.datasource.username=prod_user

spring.datasource.password=prod_pass

7. Built-in Security

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-security</artifactId>

</dependency>

8. Externalized Configuration

spring.datasource.url=jdbc:mysql://localhost:3306/mydb

spring.datasource.username=root

spring.datasource.password=secret

9. Streamlined Dependency Management

10. Faster Development and Prototyping



Q12. What is the Starting Point of a Spring Boot Application? 


The starting point of a Spring Boot application is the main class that contains the main method. This class is annotated with @SpringBootApplication, which triggers the auto-configuration and component scanning features of Spring Boot.

Breakdown of the Starting Point:

Here's an example:

@SpringBootApplication

public class MySpringBootApplication {

    public static void main(String[] args) {

        SpringApplication.run(MySpringBootApplication.class, args);

    }

}

Example:

public static void main(String[] args) {

    SpringApplication.run(MySpringBootApplication.class, args);

}

Additional Details:

Example Spring Boot Main Class:


package com.example;


import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication

public class MySpringBootApplication {

    public static void main(String[] args) {

        SpringApplication.run(MySpringBootApplication.class, args);

    }

}

Summary:



Q13. What is Singleton Design Pattern? 

The Singleton Design Pattern ensures that a class has only one instance and provides a global point of access to that instance. In other words, no matter how many times a class is accessed or called, it will always return the same instance.

Key Features of Singleton Design Pattern:

Example:


public class Singleton {

    private static Singleton instance;

    

    // Private constructor to restrict instantiation

    private Singleton() {}

    

    // Method to return the single instance (lazy initialization)

    public static Singleton getInstance() {

        if (instance == null) {

            instance = new Singleton();

        }

        return instance;

    }

}


In Spring, the default scope of a bean is singleton, meaning Spring will create only one instance of the bean per Spring container, regardless of how many times it is injected or accessed.



Q14. Are Spring Beans Thread-Safe? How does Spring handle concurrency in Singleton beans? 


No, Spring beans are not inherently thread-safe, especially when using the singleton scope (the default scope). Since the singleton scope ensures a single instance of a bean is shared across multiple threads, it can lead to concurrency issues if the bean maintains any mutable state. This is a concern for shared resources like variables, collections, or external services that the singleton instance might manipulate.

Why Spring Singleton Beans Are Not Thread-Safe:

When is Thread-Safety a Concern?

Example:


How does Spring handle concurrency in Singleton beans

Since singleton beans are shared across multiple threads, Spring does not automatically manage concurrency for singleton beans. Instead, Spring provides tools and patterns that allow you to handle concurrency explicitly:

1. Immutability (Preferred Option):

public class MyService {

    public String processData(String input) {

        return input.toUpperCase();

    }

}

2. Synchronized Blocks/Methods:

public class MyService {

    private List<String> sharedList = new ArrayList<>();

    

    public synchronized void addData(String data) {

        sharedList.add(data);

    }

}

3. Thread-Local Variables:


public void setValue(String value) {

    threadLocal.set(value);

}


public String getValue() {

    return threadLocal.get();

}

4. Prototype Scope for Stateful Beans:

@Component

public class StatefulService {

    private String state;

    

    public void setState(String state) {

        this.state = state;

    }

    

    public String getState() {

        return this.state;

    }

}

5. Concurrency Libraries:

public class ConcurrentService {

    private ConcurrentMap<String, String> cache = new ConcurrentHashMap<>();

    

    public String getData(String key) {

        return cache.get(key);

    }

    

    public void putData(String key, String value) {

        cache.put(key, value);

    }

}



Q15. What is the Difference between @RequestMapping and @GetMapping? Can you provide examples of when to use each? 



Example:


@GetMapping("/users")  // Equivalent to @RequestMapping(value = "/users", method = RequestMethod.GET)



Q16. Difference between @Controller and @RestController: How does the response type differ between the two? 




Q17. What is Logging? What is springboots default logging framework? 





Q18. What are Levels of Logging? 



Q19. How do you configure logging in a Spring Boot application? 

logging.level.com.example=DEBUG

logging.file.name=logs/spring-boot-application.log



Example:


<configuration>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">

        <file>myApp.log</file>

        <encoder>

            <pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n</pattern>

        </encoder>

    </appender>

    <root level="INFO">

        <appender-ref ref="FILE" />

    </root>

</configuration>



Q20. What other Logging Tools are used for logging?




Q21. What is @ComponentScan Annotation? What happens if you don’t specify a @ComponentScan




Q22. Build Tools (Maven, Gradle): How do Maven and Gradle differ in terms of dependency management? 




Example:

<dependency>

  <groupId>org.springframework.boot</groupId>

  <artifactId>spring-boot-starter-web</artifactId>

</dependency>




Example (Groovy):

implementation 'org.springframework.boot:spring-boot-starter-web'



Q23. Can we create Non-Web Applications in Spring Boot?




In application.properties:

spring.main.web-application-type=none


In your main class:

@SpringBootApplication

public class MyApp {

    public static void main(String[] args) {

        SpringApplication.run(MyApp.class, args);

    }

}



Q24. What is RestTemplate?




Example of RestTemplate Usage:


@RestController

public class UserController {


    @Autowired

    private RestTemplate restTemplate;


    @GetMapping("/get-user")

    public String getUser() {

        String url = "https://api.example.com/users/1";

        return restTemplate.getForObject(url, String.class);

    }

}



Q25. What is Swagger?




Q26. How to Integrate Swagger with Spring Boot?


Swagger is a widely-used tool for generating interactive API documentation for RESTful web services. It allows you to visualize and test APIs directly from the browser. In a Spring Boot application, you can easily integrate Swagger using Springfox or Springdoc OpenAPI (recommended for recent Spring Boot versions).

Here's a step-by-step guide to integrating Swagger with Spring Boot using Springdoc OpenAPI, which supports the latest Spring Boot versions:

1. Add the Springdoc OpenAPI Dependency

First, you need to add the springdoc-openapi-ui dependency to your pom.xml (for Maven) or build.gradle (for Gradle).

Maven:


<dependency>

    <groupId>org.springdoc</groupId>

    <artifactId>springdoc-openapi-ui</artifactId>

    <version>1.7.0</version>

</dependency>


Gradle:


implementation 'org.springdoc:springdoc-openapi-ui:1.7.0'


This dependency includes both OpenAPI and Swagger UI.

2. Annotate Your Controllers

Swagger automatically generates documentation for all endpoints in your Spring Boot application that are exposed via @RestController or @Controller. You don’t need to annotate your controller classes or methods specifically for Swagger unless you want to customize the documentation.

Here’s an example of a simple REST controller:


@RestController

@RequestMapping("/api")

public class UserController {


    @GetMapping("/users")

    public List<User> getAllUsers() {

        // Logic to return a list of users

    }


    @PostMapping("/users")

    public User createUser(@RequestBody User user) {

        // Logic to create a new user

    }

}


Swagger will automatically detect these endpoints and include them in the generated API documentation.

3. Access the Swagger UI

Once the application is running, you can access the Swagger UI at the following URL:

http://localhost:8080/swagger-ui.html


This interface provides a graphical representation of your API, allowing you to test each endpoint, view request/response schemas, and understand input parameters and response types.

4. Customizing Swagger Documentation

You can further customize the Swagger documentation by using annotations like @Operation, @ApiResponses, and @ApiResponse from the OpenAPI annotations.

For example:

import io.swagger.v3.oas.annotations.Operation;

import io.swagger.v3.oas.annotations.responses.ApiResponse;

import io.swagger.v3.oas.annotations.responses.ApiResponses;


@RestController

@RequestMapping("/api")

public class UserController {


    @Operation(summary = "Get all users", description = "Fetch all users from the system")

    @ApiResponses(value = {

        @ApiResponse(responseCode = "200", description = "Successfully retrieved list of users"),

        @ApiResponse(responseCode = "404", description = "Users not found")

    })

    @GetMapping("/users")

    public List<User> getAllUsers() {

        // Logic to return a list of users

    }

}


5. Customizing API Info (Optional)

You can customize the API information (e.g., title, description, version) by adding a configuration class.


import io.swagger.v3.oas.models.info.Info;

import io.swagger.v3.oas.models.OpenAPI;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;


@Configuration

public class SwaggerConfig {


    @Bean

    public OpenAPI customOpenAPI() {

        return new OpenAPI()

            .info(new Info()

                .title("My API")

                .version("1.0")

                .description("This is a sample Spring Boot API documentation"));

    }

}


6. Additional Features of Springdoc OpenAPI:


Key URLs After Integration:


Example Application with Swagger:

Here's a full example integrating Swagger with Spring Boot:

pom.xml Dependency:


<dependency>

    <groupId>org.springdoc</groupId>

    <artifactId>springdoc-openapi-ui</artifactId>

    <version>1.7.0</version>

</dependency>


UserController.java:


import org.springframework.web.bind.annotation.*;

import io.swagger.v3.oas.annotations.Operation;

import io.swagger.v3.oas.annotations.responses.ApiResponse;

import io.swagger.v3.oas.annotations.responses.ApiResponses;


import java.util.List;


@RestController

@RequestMapping("/api")

public class UserController {


    @Operation(summary = "Get all users", description = "Fetch all users from the system")

    @ApiResponses(value = {

        @ApiResponse(responseCode = "200", description = "Successfully retrieved list of users"),

        @ApiResponse(responseCode = "404", description = "Users not found")

    })

    @GetMapping("/users")

    public List<User> getAllUsers() {

        // Logic to return a list of users

    }


    @PostMapping("/users")

    public User createUser(@RequestBody User user) {

        // Logic to create a new user

    }

}


SwaggerConfig.java (Optional):


import io.swagger.v3.oas.models.OpenAPI;

import io.swagger.v3.oas.models.info.Info;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;


@Configuration

public class SwaggerConfig {


    @Bean

    public OpenAPI customOpenAPI() {

        return new OpenAPI()

            .info(new Info().title("User Management API").version("1.0").description("API for managing users"));

    }

}


Conclusion:

Integrating Swagger with Spring Boot using Springdoc OpenAPI is simple and powerful. It automatically generates API documentation for your controllers and exposes a user-friendly UI for exploring and interacting with your API. This setup also supports customization through annotations, making it a valuable tool for API development and testing.



Q27. What are Spring Profiles? What is the purpose of spring.profiles.active?


Spring Profiles allow developers to segregate parts of the application configuration based on different environments (e.g., development, testing, production). They enable switching between different configurations (such as database settings, API credentials, or external service endpoints) without changing the source code, making the application more flexible and maintainable.

Profiles in Spring are essentially a way to organize and isolate beans and configurations so that they are only active in a specific environment.


Key Use Cases:


How to Define and Use Profiles in Spring?

1. Defining Beans with Profiles:

You can annotate beans with @Profile to specify that they should only be created when a specific profile is active.

Example:

@Configuration

public class DataSourceConfig {


    @Bean

    @Profile("dev")

    public DataSource devDataSource() {

        // Configuration for development database (e.g., H2)

        return new H2DataSource();

    }


    @Bean

    @Profile("prod")

    public DataSource prodDataSource() {

        // Configuration for production database (e.g., PostgreSQL)

        return new PostgreSQLDataSource();

    }

}


In this example:


2. Application Properties for Profiles:

You can create profile-specific properties files to configure environment-specific settings, such as application port, database URLs, or logging levels.

Example: 

application-dev.properties

server.port=8081

spring.datasource.url=jdbc:h2:mem:testdb

spring.datasource.username=sa

spring.datasource.password=


application-prod.properties

server.port=8080

spring.datasource.url=jdbc:postgresql://localhost:5432/mydb

spring.datasource.username=prod_user

spring.datasource.password=prod_password



What is spring.profiles.active?

The spring.profiles.active property is used to activate one or more profiles in Spring. This property tells Spring which profile(s) should be active during the application runtime.

You can set spring.profiles.active in multiple ways, such as:

In the application properties file:

spring.profiles.active=dev

As a JVM System Property: You can pass the profile while starting the application:

java -jar myapp.jar --spring.profiles.active=prod


As an Environment Variable: Set an environment variable to activate the profile:

export SPRING_PROFILES_ACTIVE=prod


Programmatically: You can activate profiles in Java code.

public static void main(String[] args) {

    SpringApplication app = new SpringApplication(MyApplication.class);

    app.setAdditionalProfiles("prod");

    app.run(args);

}


Multiple Profiles:

You can activate multiple profiles by comma-separating them:


spring.profiles.active=dev,aws


In this case, both the dev and aws profiles will be active, and beans or configurations related to both profiles will be loaded.


Example Scenario:

Consider a scenario where you need different configurations for development, test, and production environments.

1. application-dev.properties:


server.port=8081

spring.datasource.url=jdbc:h2:mem:testdb

logging.level.root=DEBUG


2. application-prod.properties:


server.port=8080

spring.datasource.url=jdbc:postgresql://localhost:5432/prod_db

logging.level.root=INFO


3. Activate the Profile:

To run the application in production mode, you can set spring.profiles.active to prod:


spring.profiles.active=prod


This ensures that the production settings from application-prod.properties are applied.

Benefits of Using Spring Profiles:

Conclusion:




Q28. What is the Default Application Server of Spring Boot. Can we replace Apache Tomcat with some other App Server?






In pom.xml, exclude Tomcat:


<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>


Add the Jetty dependency:


<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-jetty</artifactId>

</dependency>



Q29. What are Cascade Types and Examples with Pros and Cons?





Example:


import javax.persistence.*; 


@Entity 

public class User { 


@Id 

@GeneratedValue(strategy = GenerationType.IDENTITY) 

private Long id; 


@OneToMany(cascade = CascadeType.PERSIST) // Persist operations will cascade 

private List<Order> orders; 


@Entity 

public class Order { 

@Id 

@GeneratedValue(strategy = GenerationType.IDENTITY) 

private Long orderId; 


// Other fields 





Q30. How to handle Transactional Management in Spring Boot?



Example:


@Transactional

public void saveUser(User user) {

    userRepository.save(user);

// Any additional operations on the database

}




Q31. Explain Transactional Propagation and Its Types with Examples:




Example:


@Transactional(propagation = Propagation.REQUIRES_NEW)

public void createUser(User user) {

    userRepository.save(user);

}


@Transactional(propagation = Propagation.REQUIRED)

public void updateUser(User user) { ... }



Q32. Flow of API Requests in Spring:




Q33. What are Fetch Types (EAGER and LAZY) and Their Use Cases?




Example:


import javax.persistence.*; 


@Entity 

public class User { 


@Id 

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id; 


@OneToMany(fetch = FetchType.EAGER) // Will load User's Orders beforehand

private List<Order> orders;



@Entity 

public class Order { 


@Id 

@GeneratedValue(strategy = GenerationType.IDENTITY) 

private Long orderId; 


// Other fields 




Example:


import javax.persistence.*; 


@Entity 

public class User { 


@Id 

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id; 


@OneToMany(fetch = FetchType.LAZY) // Will load User's Orders on demand 

private List<Order> orders; 



@Entity 

public class Order { 


@Id 

@GeneratedValue(strategy = GenerationType.IDENTITY) 

private Long orderId; 


// Other fields 




Q34. Explain @Autowired:




Q35. What is Global Exception Handling? Explain @ExceptionHandler and @ControllerAdvice:





Example:


@ControllerAdvice

public class GlobalExceptionHandler {


    @ExceptionHandler(ResourceNotFoundException.class)

    public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException ex) {

        ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), "Resource Not Found");

        return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);

    }


    @ExceptionHandler(Exception.class)

    public ResponseEntity<?> handleGlobalException(Exception ex) {

        ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), "Internal Server Error");

        return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);

    }

}


You can define a custom exception like ResourceNotFoundException to handle scenarios where a resource is not found:


public class ResourceNotFoundException extends RuntimeException {

    public ResourceNotFoundException(String message) {

        super(message);

    }

}



Q36. What are REST API Properties and HTTP Verbs? What is the difference between PUT and PATCH Mapping:






Q37. Explain SOLID Design Principles:









Q38. Explain following Design Patterns - Singleton, Factory, Decorator, Strategy, Observable, Adapter, Flyweight, Command, Chain of Responsibility:




Q39. Multithreading with Singleton Bean:




Q40. Explain Immutability:



Example in Java:

public final class ImmutableUser {

    private final String name;

    public ImmutableUser(String name) {

        this.name = name;

    }

    public String getName() {

        return name;

    }

}



Q41. Explain Streaming?




Q42. Explain Messaging:




Q43. Caching:




Example:

@Cacheable("users")

public User getUserById(Long id) {

    return userRepository.findById(id).orElse(null);

}



Q44. Explain Security - SSL, JWT, OAuth:


Provides secure communication by encrypting data between the client and server. In Spring Boot, SSL can be enabled by configuring the application.properties:


server.ssl.key-store=classpath:keystore.p12

server.ssl.key-store-password=password



A compact and self-contained way of securely transmitting information between parties as a JSON object.




OAuth2 is a protocol for delegated authorization. Spring Boot integrates OAuth2 to allow third-party services (like Google or GitHub) to access your application securely.




Q45. How to Create a Customized Starter in Spring Boot:





Q46. What are Spring Boot Peer Technologies?






Q47. How to implement Paging and Sorting with Pageable and Sort?



Using Pageable: Pageable is used to specify the page size, the current page number, and the sorting order(optional).


@GetMapping("/users")

public Page<User> getUsers() {

    Pageable pageable = PageRequest.of(0, 10); // Page 0 with 10 items per page

    return userRepository.findAll(pageable);

}


Using Sort: You can specify sorting criteria using the Sort class.


@GetMapping("/users")

public List<User> getUsers(Sort sort) {

    return userRepository.findAll(sort);

}



Pageable pageable = PageRequest.of(0, 10, Sort.by("lastName").ascending());

Page<User> users = userRepository.findAll(pageable);



Q48. What is @Entity Annotation



Example


@Entity

public class User {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;


    private String name;

    // Other fields and getters/setters

}



Q49. What is a Spring Configuration Class



Example


@Configuration

public class AppConfig {


    @Bean

    public DataSource dataSource() {

        return new HikariDataSource();

    }

}



Q50. What is Datasource Bean



Example

You can define a DataSource bean in your configuration class:

@Bean

public DataSource dataSource() {

    DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();

    dataSourceBuilder.url("jdbc:mysql://localhost:3306/mydb");

    dataSourceBuilder.username("root");

    dataSourceBuilder.password("password");

    return dataSourceBuilder.build();

}



Q51. What is @Query Annotation



Example


@Query("SELECT u FROM User u WHERE u.email = ?1")

User findByEmail(String email);


You can also use native queries:

@Query(value = "SELECT * FROM users WHERE email = ?1", nativeQuery = true)

User findByEmailNative(String email);



Q52. What is Eureka Server



Configuring Eureka


Add the following dependency to your pom.xml:

<dependency>

    <groupId>org.springframework.cloud</groupId>

    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>

</dependency>


Enable Eureka Server


Annotate your main application class with @EnableEurekaServer:

@SpringBootApplication

@EnableEurekaServer

public class EurekaServerApplication { ... }



Q53. What is Docker? What are the Benefits of Docker






Q54. What are the steps of Dockerizing a Spring Boot Application




Example Dockerfile:

FROM openjdk:17-jdk-alpine

VOLUME /tmp

ARG JAR_FILE=target/*.jar

COPY ${JAR_FILE} app.jar

ENTRYPOINT ["java","-jar","/app.jar"]



Run the following command in the directory containing the Dockerfile:


docker build -t my-spring-boot-app .



To run the app inside a Docker container:


docker run -p 8080:8080 my-spring-boot-app



Q55. What is Docker Compose


Docker Compose is used to define and run multi-container Docker applications (e.g., running your Spring Boot app along with a database).


Example docker-compose.yml for running a Spring Boot app with a MySQL database:

version: '3'

services:

  app:

    image: my-spring-boot-app

    ports:

      - "8080:8080"

    depends_on:

      - db

  db:

    image: mysql:8

    environment:

      MYSQL_ROOT_PASSWORD: root

      MYSQL_DATABASE: mydb


Run both services using: docker-compose up



Q56. What is Kubernetes






Q57. What are the steps of Deploying Spring Boot on Kubernetes



kind: Deployment

metadata:

  name: spring-boot-deployment

spec:

  replicas: 3

  selector:

    matchLabels:

      app: spring-boot

  template:

    metadata:

      labels:

        app: spring-boot

    spec:

      containers:

      - name: spring-boot-container

        image: my-spring-boot-app

        ports:

        - containerPort: 8080


kind: Service

metadata:

  name: spring-boot-service

spec:

  selector:

    app: spring-boot

  ports:

    - protocol: TCP

      port: 8080

      targetPort: 8080

  type: LoadBalancer



Apply the deployment and service files:

kubectl apply -f deployment.yml

kubectl apply -f service.yml



Q58. How can we Scale Spring Boot application in Kubernetes


Kubernetes automatically scales your Spring Boot application based on demand. For instance, you can scale your app by increasing the number of replicas:


kubectl scale deployment spring-boot-deployment --replicas=5



Q59. What is the purpose of Health Monitoring




Q60. What are some Monitoring Tools




Q61. What is Spring Boot Actuator?






    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-actuator</artifactId>

</dependency>



Q62. How will you integrate Prometheus and Grafana in your SpringBoot Application




    <groupId>io.micrometer</groupId>

    <artifactId>micrometer-registry-prometheus</artifactId>

</dependency>





Q63. Docker + Kubernetes Integration with CI/CD





Q64. What is MappedSuperClass? Explain with code

MappedSuperclass is a class that provides common mappings to its subclasses. It’s not an entity itself but allows shared fields in subclasses.

Example Code:


import javax.persistence.*;


@MappedSuperclass

public abstract class BaseEntity {


    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;


    private String createdAt;

    private String updatedAt;


    // Getters and Setters

}


@Entity

public class User extends BaseEntity {

    private String username;

}


@Entity

public class Product extends BaseEntity {

    private String productName;

}


Q65. What is @RestController and @RequestMapping? Explain with code

@RestController is a specialized version of the @Controller annotation that combines @ResponseBody and @Controller, making it suitable for RESTful web services.

@RequestMapping is used to map HTTP requests to handler methods in your controller.

Example Code:

import org.springframework.web.bind.annotation.*;


@RestController

@RequestMapping("/api/products")

public class ProductController {


    @GetMapping

    public List<Product> getAllProducts() {

        // Logic to fetch products

        return productService.fetchProducts();

    }


    @PostMapping

    public Product createProduct(@RequestBody Product product) {

        // Logic to create a new product

        return productService.saveProduct(product);

    }

}


Q66. Fetch a list of products from a third-party API using RestTemplate. Once the products are retrieved, you need to store them in your local database.

Here’s a complete structure to fetch products and store them in a local database using Spring Boot:

Project Structure:

src

└── main

    ├── java

    │   └── com

    │       └── example

    │           ├── ProductApplication.java

    │           ├── controller

    │           │   └── ProductController.java

    │           ├── entity

    │           │   └── Product.java

    │           ├── repository

    │           │   └── ProductRepository.java

    │           └── service

    │               └── ProductService.java

    └── resources

        └── application.properties


1. ProductApplication.java:

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication

public class ProductApplication {

    public static void main(String[] args) {

        SpringApplication.run(ProductApplication.class, args);

    }

}


2. Product.java (Entity):

import javax.persistence.*;

@Entity

public class Product {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;

    private String name;

    private String description;

    // Getters and Setters

}


3. ProductRepository.java (Repository):

import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Long> {

}


4. ProductService.java (Service):

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service

public class ProductService {

    @Autowired

    private RestTemplate restTemplate;

    @Autowired

    private ProductRepository productRepository;

    public void fetchAndStoreProducts() {

        String url = "https://api.example.com/products"; // Replace with actual API URL

        Product[] products = restTemplate.getForObject(url, Product[].class);

        if (products != null) {

            for (Product product : products) {

                productRepository.save(product);

            }

        }

    }

}


5. ProductController.java (Controller):


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;


@RestController

@RequestMapping("/api/products")

public class ProductController {

    @Autowired

    private ProductService productService;


    @PostMapping("/fetch")

    public void fetchProducts() {

        productService.fetchAndStoreProducts();

    }

}


6. application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/your_database

spring.datasource.username=your_username

spring.datasource.password=your_password

spring.jpa.hibernate.ddl-auto=update


7. RestTemplate Configuration:

You need to configure RestTemplate as a bean:


import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.client.RestTemplate;


@Configuration

public class AppConfig {

    @Bean

    public RestTemplate restTemplate() {

        return new RestTemplate();

    }

}


Summary

This complete structure includes fetching a list of products from a third-party API using RestTemplate and saving them into a local database using Spring Boot. Make sure to replace the API URL and database configuration with actual values.