KEMBAR78
Springboot Interview | PDF | Databases | Computer Programming
0% found this document useful (0 votes)
11 views21 pages

Springboot Interview

The document provides an overview of Spring Core, Maven, Spring Boot, and Spring Data JPA, detailing concepts such as Inversion of Control, Dependency Injection, and the differences between BeanFactory and ApplicationContext. It also covers Spring Boot's auto-configuration, REST API handling, and JPA features like projections and auditing. Additionally, it highlights the advantages of using Spring and Spring Data JPA in application development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views21 pages

Springboot Interview

The document provides an overview of Spring Core, Maven, Spring Boot, and Spring Data JPA, detailing concepts such as Inversion of Control, Dependency Injection, and the differences between BeanFactory and ApplicationContext. It also covers Spring Boot's auto-configuration, REST API handling, and JPA features like projections and auditing. Additionally, it highlights the advantages of using Spring and Spring Data JPA in application development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Spring Core and Maven

Q1. What is Inversion of Control (IoC) and how is it implemented in Spring?


Answer:
IoC is a design principle where the control of object creation is transferred from the
application to the framework. In Spring, it’s implemented using Dependency Injection
through annotations like @Autowired, constructor injection, or XML configuration.

Q2. What are the di erences between BeanFactory and ApplicationContext?


Answer:

 BeanFactory is the basic IoC container and is lazily initialized.

 ApplicationContext is a more advanced container with additional features like


event propagation, internationalization, and eager initialization.

Noteworthy:
Use ApplicationContext over BeanFactory in most cases.

Q3. What is AOP in Spring?


Answer:
AOP (Aspect-Oriented Programming) allows you to define cross-cutting concerns like
logging and security separately from business logic using advice, pointcuts, aspects etc.

Q4. List a few advantages of using Spring.


Answer:

 Simplified Java EE development

 Loose coupling via DI

 Modular architecture

 Testability

 Integration with other frameworks


Q5. What is Maven and why is it used in Spring applications?
Answer:
Maven is a build automation tool used for managing a project’s build, dependencies, and
lifecycle. In Spring, Maven helps in automatically downloading Spring libraries and
managing versions, thereby reducing manual e orts.

Q1. What are the di erent ways to define beans in Spring?


Answer:
Beans can be defined using:

1. XML (<bean> tag)

2. Annotation-based (@Component, @Service, etc.)

3. Java-based (@Bean inside @Configuration class)

Q2. What is @ComponentScan and why is it used?


Answer:
@ComponentScan tells Spring to scan a package for classes annotated with stereotype
annotations like @Component, @Service, @Repository, and register them as beans.

Q3. What is the di erence between @Component and @Bean?


Answer:

 @Component is used on the class level and discovered through classpath


scanning.

 @Bean is used on methods inside a @Configuration class to manually define


beans.

Q1. What is ORM and how is it used in Spring?


Answer:
ORM maps Java objects to database tables. Spring integrates ORM frameworks like
Hibernate or JPA using the Spring ORM module and provides @Repository-based DAOs or
Spring Data JPA interfaces.
Q1. What is Spring Boot and how is it di erent from Spring?
Answer:
Spring Boot simplifies Spring development by o ering auto-configuration, embedded
servers, and starter dependencies. It requires minimal configuration and helps in quickly
creating stand-alone applications.

Q2. What is the use of @SpringBootApplication?


Answer:
It is a combination of @Configuration, @ComponentScan, and
@EnableAutoConfiguration. It marks the main class as the configuration and entry point for
the Spring Boot application.

Q3. What is auto-configuration in Spring Boot?


Answer:
Auto-configuration automatically sets up Spring beans and settings based on the
dependencies on the classpath and predefined defaults, reducing the need for manual
configuration.

Q4. What is the purpose of application.properties or application.yml?


Answer:
These files are used to customize Spring Boot configurations like server port, database
details, logging levels, etc.

Q5. What is "convention over configuration"?


Answer:
It means Spring Boot provides sensible defaults and developers don’t need to configure
everything unless they want to change the default behavior.
Spring Data JPA With SpringBoot, Hibernate
Q1. What is Spring Data JPA?
Answer:
Spring Data JPA is a library that builds on top of JPA to simplify data access by auto-
generating repository implementations and integrating seamlessly with Spring Boot.

Q2. What is the di erence between JPA and Spring Data JPA?
Answer:

 JPA is a specification (API) for ORM.

 Spring Data JPA is an abstraction over JPA that simplifies CRUD operations, query
generation, and reduces code.

Q3. What is JpaRepository?


Answer:
JpaRepository is a Spring Data interface that extends CrudRepository and
PagingAndSortingRepository, and adds extra JPA-specific functionality.

Q4. What are the advantages of using Spring Data JPA in Spring Boot?
Answer:

 Less boilerplate

 Auto-configured database setup

 Easy method-based query generation

 Built-in pagination and sorting

 Easy integration with Spring Boot apps


Q5. How do you write custom queries in Spring Data JPA?
Answer:
Using:

 Method name conventions (findByName, findByAgeGreaterThan)

 @Query annotation for JPQL or native SQL

Q1. How do you set up Spring Data JPA in a Spring Boot project?
Answer:

 Add spring-boot-starter-data-jpa and a database dependency (like H2 or MySQL)

 Configure DB properties in application.properties

 Define @Entity classes and JpaRepository interfaces

Q2. What does spring.jpa.hibernate.ddl-auto=update do?


Answer:
It updates the database schema automatically based on the current entity classes without
dropping data.

Q3. How does Spring Boot auto-configure JPA?


Answer:
Spring Boot detects spring-boot-starter-data-jpa on the classpath and auto-configures
EntityManagerFactory, DataSource, and JPA transaction management using default or
provided properties.

Q1. What is an Entity in JPA?


Answer:
An entity is a Java class mapped to a database table using @Entity. It represents the
application's persistent data.
Q2. How do you define a primary key in a JPA entity?
Answer:
By using the @Id annotation on a field, and optionally @GeneratedValue to auto-generate
the key.

Q3. What is the purpose of @Table annotation?


Answer:
To specify the table name if it is di erent from the class name.

Q4. Explain @OneToMany and @ManyToOne in JPA.


Answer:
@OneToMany represents a collection of child entities mapped from one parent.
@ManyToOne represents the reverse relationship where many entities refer to one parent.

Q5. How does @GeneratedValue work in JPA?


Answer:
It specifies how the primary key should be generated. Strategies include AUTO, IDENTITY,
SEQUENCE, and TABLE.

Q1. What is the role of Spring Data repositories?


Answer:
They provide a high-level abstraction over the persistence layer, allowing CRUD and query
operations without implementing them manually.

Q2. How does Spring Data generate queries from method names?
Answer:
Spring parses method names like findByEmail, interprets the field (email), condition
(findBy), and generates the corresponding JPQL query.
Q3. When would you use the @Query annotation?
Answer:
When:

 Query method naming becomes too complex

 You want fine-grained control over query structure

 You want to use JPQL or native SQL

Q4. How do you implement a custom method in a repository?


Answer:

 Define a custom interface

 Create an implementation class with Impl su ix

 Extend it in your main repository

Q1. How do you perform CRUD using Spring Data JPA?


Answer:
By creating a repository interface that extends JpaRepository, and using built-in methods like
save(), findAll(), deleteById(), and findById().

Q2. What is the return type of findById()?


Answer:
It returns Optional<T> which handles nulls safely and avoids NullPointerException.

Q3. How does save() work for both insert and update?
Answer:
If the entity's ID is null, it performs an insert; if the ID exists, it performs an update.
Q1. How does Spring Data JPA generate queries from method names?
Answer:
Spring uses a parser to interpret method names like findByEmailAndAge, map them to
entity fields, and generate JPQL at runtime.

Q2. What is the difference between @Query and @NamedQuery?


Answer:

 @NamedQuery: Defined statically on the entity class; reused across the app.
 @Query: Defined on the repository interface; can be JPQL or native and is easier to
use for one-off queries.

Q3. When should you use @Query instead of method names?


Answer:
When:

 Query logic is complex


 You need joins or aggregations
 You need to use native SQL

Q4. What are the benefits of query methods?


Answer:

 Readable and declarative


 No need to write actual SQL
 Maintained easily
 Supports many operations (filters, sort, pagination)

Q5. Can you use native SQL with @Query?


Answer:
Yes, by setting nativeQuery = true in the annotation.
Q6. What happens when you provide a page number that exceeds the total number of
pages?
Answer:
Spring Data JPA returns an empty Page object — no exception is thrown.

Q1. What is the use of auditing in JPA?


Answer:
Auditing helps in tracking metadata like who created or modified an entity and when it was
done — useful for maintaining history and accountability.

Q2. How does Spring Data JPA support auditing?


Answer:
Spring provides annotations like @CreatedDate, @LastModifiedDate, @CreatedBy, and
@LastModifiedBy which are automatically populated when auditing is enabled using
@EnableJpaAuditing.

Q3. What does the AuditorAware<T> interface do?


Answer:
It provides the current user’s identity (auditor) at runtime, which is used to populate
@CreatedBy and @LastModifiedBy.

Q4. Can you use auditing without Spring Security?


Answer:
Yes. You can manually return a fixed or programmatic value in your AuditorAware
implementation.

Q5. Is it mandatory to use all four annotations (@CreatedBy, @CreatedDate, etc.)?


Answer:
No. You can choose only the ones you need — e.g., just @CreatedDate and
@LastModifiedDate for timestamp tracking.
Q1. What are JPA projections and when should you use them?
Answer:
JPA projections are a way to fetch only the required subset of fields from an entity. You should
use them when:

 You want better performance


 You want to avoid exposing sensitive fields
 You don’t need full entity behavior

Q2. What is the difference between interface and class-based projections?


Answer:

 Interface-based: Uses Java interface with getter methods; more declarative


 Class-based: Uses DTO with matching constructor; more flexible and customizable

Q3. What happens if a field in the projection interface doesn’t match the entity field?
Answer:
Spring will throw a runtime exception because it cannot map the field.

Q4. Can we use projections in native queries?


Answer:
Yes, but with limited support. You must use @SqlResultSetMapping or map manually in case of
class-based projections.

Q5. Is it better to use projections or entity views in large datasets?


Answer:
Projections are better when:

 You want only a subset of fields


 You want optimized queries
 You don't need lazy-loaded relationships or entity behavior
Q1. How does Spring Boot simplify JPA integration?
Answer:
By using auto-configuration, Spring Boot automatically sets up:

 DataSource

 EntityManagerFactory

 Scans for @Entity and @Repository

 Applies config from application.properties

Q2. What is the role of spring.jpa.show-sql=true?


Answer:
It logs the generated SQL queries to the console for debugging and testing purposes.

Q3. How do you manage multiple data sources in Spring Boot?


Answer:
By:

 Defining multiple DataSource, EntityManagerFactory, and TransactionManager


beans

 Using @EnableJpaRepositories with basePackages and ref attributes

Q4. How is configuration externalized in Spring Boot?


Answer:
Using application.properties or application.yml, so environment-specific details like DB
URL, user, password, etc., are not hardcoded.

Q5. What happens if spring.jpa.hibernate.ddl-auto is not specified?


Answer:
Default behavior is none, so Spring does not manage schema unless explicitly instructed.
Q1. What is the role of Hibernate in Spring Data JPA?
Answer:
Hibernate is the JPA provider that implements the actual logic of mapping Java objects to
database tables and SQL generation.

Q2. What’s the benefit of @DynamicInsert and @DynamicUpdate?


Answer:
They improve performance by:

 Skipping null fields in INSERT

 Updating only changed fields in UPDATE

Q3. What is @BatchSize in Hibernate?


Answer:
It's used to optimize the fetching of collections or entities in batches, reducing N+1 query
problems.

Q4. Can you mix JPA annotations with Hibernate-specific ones?


Answer:
Yes. JPA annotations are standard, but Hibernate-specific annotations provide extra
features like batch size, filters, formula, etc.

Q5. How does Hibernate support pagination?


Answer:
Internally, Hibernate translates Spring’s Pageable into SQL LIMIT and OFFSET clauses.
Spring REST and Spring Boot 3
Q1. What is the di erence between @Controller and @RestController?
Answer:

 @Controller returns view (HTML/JSP).

 @RestController is shorthand for @Controller + @ResponseBody and returns data


(JSON/XML).

Q2. How does Spring handle JSON conversion?


Answer:
Spring uses Jackson by default to convert Java objects to JSON and vice versa.

Q3. What’s the role of @RequestMapping, @GetMapping, etc.?


Answer:
They map HTTP requests to handler methods.
Example: @GetMapping("/users") handles GET requests to /users.

Q4. How is Spring Boot 3 di erent from Spring Boot 2.x?


Answer:

 Requires Java 17+

 Uses Jakarta EE 9 (jakarta.*) instead of javax.*

 Supports AOT compilation, native images, and better observability

Q5. How do you handle exceptions in Spring REST API?


Answer:
Using:

 @ControllerAdvice

 @ExceptionHandler

 In Spring Boot 3, also using ProblemDetail for standard JSON error format.
Q1. What is @RestController in Spring Boot?
Answer:
A specialized version of @Controller that returns data (like JSON/XML) directly instead of
view templates.

Q2. How does Spring handle di erent HTTP methods?


Answer:
Spring provides:

 @GetMapping, @PostMapping, @PutMapping, @DeleteMapping

 These map to standard HTTP verbs automatically

Q3. How does Spring convert Java objects to JSON?


Answer:
Using Jackson (included by default in Spring Boot). The controller methods return Java
objects, which Spring auto-converts to JSON.

Q4. Can we handle multiple request types in one controller?


Answer:
Yes. You can use di erent methods inside a single controller class for GET, POST, PUT, and
DELETE.

Sample Code for simple REST controller

@RestController

@RequestMapping("/api/users")

public class UserController {

// Fake DB

private Map<Long, User> userDb = new HashMap<>();

// CREATE (POST)
@PostMapping

public String createUser(@RequestBody User user) {

userDb.put(user.getId(), user);

return "User added with ID: " + user.getId();

// READ (GET)

@GetMapping("/{id}")

public User getUser(@PathVariable Long id) {

return userDb.get(id);

// UPDATE (PUT)

@PutMapping("/{id}")

public String updateUser(@PathVariable Long id, @RequestBody User updatedUser) {

userDb.put(id, updatedUser);

return "User updated with ID: " + id;

// DELETE (DELETE)

@DeleteMapping("/{id}")

public String deleteUser(@PathVariable Long id) {

userDb.remove(id);

return "User deleted with ID: " + id;

}
Q1. What is the di erence between @RequestParam and @RequestBody?
Answer:

 @RequestParam: Extracts query parameters from URL

 @RequestBody: Parses entire request body (typically JSON) into a Java object

Q2. How do you send a custom status code or header in Spring Boot?
Answer:

 Use ResponseEntity<T> to set both HTTP status and headers programmatically.

Q3. What is the use of @ControllerAdvice in REST APIs?


Answer:
It handles exceptions globally for all controllers, keeping code clean and centralized.

Q4. What’s new in Spring Boot 3 for error handling?


Answer:
Spring Boot 3 introduces ProblemDetail, which provides structured error responses.

Q1. Why should we use DTOs instead of returning Entities directly?


Answer:
To decouple frontend from backend, hide sensitive info, prevent lazy loading errors, and
improve maintainability.

Q2. What are some ways to map Entity to DTO?


Answer:
Manually, using ModelMapper, or using MapStruct.

Q3. How do you customize JSON in Spring Boot?


Answer:
Using Jackson annotations like @JsonProperty, @JsonIgnore, @JsonFormat.
Q4. What is the advantage of API versioning?
Answer:
It allows backward compatibility when changing API structures or logic.

Q5. What’s the default JSON processor used by Spring Boot?


Answer:
Jackson (via the spring-boot-starter-json dependency)

Q1. What is the purpose of HATEOAS in RESTful APIs?


Answer:
To make the API self-descriptive by including links in responses that tell the client what
operations can be performed next.

Q2. What is the di erence between REST and REST + HATEOAS?


Answer:

 Plain REST returns data only.

 HATEOAS-enhanced REST returns data + actionable links for navigation.

Q3. How do you add HATEOAS links in Spring Boot?


Answer:
Use EntityModel, linkTo() and methodOn() to add links in controller responses.

Q4. How does HATEOAS help in API evolution?


Answer:
Clients rely on links instead of hardcoded URLs, so server-side changes (like URL structure)
don’t break the client.

Q1. How does Spring Boot determine the response format in a REST controller?
Answer:
Using content negotiation — mainly via the Accept header, URL extensions, or query
params (if enabled).
Q3. How do you return both JSON and XML from the same endpoint?
Answer:
Add the jackson-dataformat-xml dependency. Spring will auto-negotiate based on Accept
header.

Q4. Can Spring Boot produce custom media types?


Answer:
Yes, by setting produces = "application/vnd.yourapp+json" in your controller method.

Q1. What is the use of Spring Boot Actuator?


Answer:
It provides endpoints to monitor and manage Spring applications in production (health,
metrics, beans, etc.)

Q2. How do you expose only selected Actuator endpoints?


Answer:
By using management.endpoints.web.exposure.include=health,info in
application.properties.

Q3. Can you create custom metrics in Spring Boot?


Answer:
Yes, by using MeterRegistry from Micrometer.

Q4. What’s the di erence between /actuator/info and /actuator/health?


Answer:

 /actuator/info: General metadata (name, version)

 /actuator/health: Status of the app (UP/DOWN)


Q1. How does Spring Security protect endpoints?
Answer:
It uses filters to intercept requests and check for authentication & authorization based on
user roles.

Q2. What’s the di erence between authentication and authorization?


Answer:

 Authentication = Verifying identity

 Authorization = Checking access rights

Q3. Why is JWT preferred for REST APIs?


Answer:
It’s stateless, scalable, and can be verified without storing session data on the server.

Q4. How do you handle CORS issues in Spring Boot?


Answer:
By configuring allowed origins, methods, and headers via CorsRegistry or CorsFilter.

Q5. How do you secure specific URLs in Spring Security?


Answer:
Using .requestMatchers("/admin/**").hasRole("ADMIN") inside the HttpSecurity config.

Q1. What’s the di erence between @WebMvcTest and @SpringBootTest?


Answer:

 @WebMvcTest: Loads only the web (controller) layer

 @SpringBootTest: Loads the full application context (used for integration testing)
Q2. What is the purpose of MockMvc in Spring Boot testing?
Answer:
To simulate HTTP requests to controller endpoints and assert the response (status, JSON,
headers)

Q3. Why do we mock services in controller tests?


Answer:
To isolate the controller logic from service/database logic, ensuring fast, independent tests

Q4. How can you verify JSON content in a response?


Answer:
Using jsonPath() in MockMvcResultMatchers

Q5. What is the benefit of @MockBean in Spring Boot tests?


Answer:
It replaces a Spring bean with a Mockito mock, allowing you to control its behavior for
testing.

Q1. What is Swagger and why is it used?


Answer:
Swagger (now OpenAPI) is used to auto-generate documentation and provide a UI to
explore, test, and integrate REST APIs.

Q2. How do you add Swagger documentation to a Spring Boot app?


Answer:
By adding the springdoc-openapi-starter-webmvc-ui dependency and annotating your
controller methods.

Q3. What is the di erence between Swagger and Postman?


Answer:

 Swagger: Auto-generates docs and interactive UI from code

 Postman: Manual tool to test APIs, write test scripts


Q4. How can you hide internal APIs from Swagger docs?
Answer:
Use @Hidden annotation on methods or controllers.

Q5. What’s the benefit of using @Schema and @Tag annotations?


Answer:
Improves structure, grouping, and readability of API documentation.

You might also like