Spring Boot Interview Questions
Spring Boot Interview Questions
java framework
provide RAD
Dependency management
Easy to use
Production ready applications: It provides many tools for production ready applications like
Actuators
@SpringBootApplication
@Component
1. Using it we can make any class as a component so that it will consider as a spring
bean
2. And we can ask bean from that application context.getBean(Student.class) gives
object
3. Error : No qualifying bean of type ( ) No bean definition exception (occurs if we
don’t put @Component on a class or bean)
@Autowired
8) What is Spring-boot-starter-parents
9)Can we use only spring boot dependency feature and configure maven plugin manually.
10) What is spring boot CLI & what are benefits?
https://docs.spring.io/spring-boot/installing.html#getting-started.installing.cli
- spring version
- spring help
- spring init
Lifecycle means how objects are born from start to end, and how it behaves and how it ends.
16) What is difference between the setter and constructor injection in Spring?
- Both does same things but use @Inject when to standardize the dependency injection and
@Autowire is only for Spring specific.
- Like JVM is standard and jdk are specific (openjdk, eclipse, ibm).
- Component is preferable for component scanning and spring scans is automatically and auto
wiring
- If you want to create a logic that how it behaves, like @Bean gives object that spring should
register as a bean in application context. In that method body we can write how instance is
created.
Here we want bean of Network in Phone class, but if you use @Component then it will
happen directly. But if we are using @Bean then now that method has a logic and
responsibility to create and return an object as a bean. Also required @Configuration
annotation on a class which has methods as @Bean annotated.
20) What is auto wiring in spring? What are auto wiring modes?
21) What are different bean scopes in spring?
Connection pooling is a technique used in Spring Boot applications to manage database connections
efficiently. It helps improve application performance and reduces the overhead of creating and
destroying database connections repeatedly.
3. Thread Safety: Ensures that multiple threads can use database connections without
conflicts.
2. When a thread needs a connection, it borrows one from the pool instead of creating a new
one.
3. After the thread finishes its operation, the connection is returned to the pool.
xml
Copy code
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
properties
Copy code
# Datasource configuration
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# HikariCP-specific settings
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.minimum-idle=2
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.connection-timeout=20000
spring.datasource.hikari.max-lifetime=1800000
Copy code
@RestController
@Autowired
@GetMapping("/test-connection-pool")
} catch (Exception e) {
1. Optimize Pool Size: Set maximum-pool-size based on application needs and database
capacity.
3. Connection Timeout: Set a proper connection-timeout to avoid threads waiting too long.
4. Monitoring: Use metrics to monitor the pool's health. For HikariCP, use tools like Spring
Actuator.
Comparison Table
Conclusion
HikariCP is the most efficient and widely used connection pooling library for Spring Boot applications.
It’s the default and best choice for most use cases. Adjust configurations based on your application's
specific requirements.
Problem:
Initially, the application faced performance bottlenecks during peak hours.
Symptoms: Slow response times and occasional downtime.
Root Cause: Upon investigation, I found that the application created a new database
connection for each request. This led to resource exhaustion on the database server and
delayed responses.
Solution:
1. Implemented Connection Pooling:
I configured HikariCP, the default connection pooling library in Spring Boot, to reuse
database connections instead of creating and closing them repeatedly.
properties
Copy code
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.idle-timeout=60000
spring.datasource.hikari.max-lifetime=1800000
2. Optimized Pool Settings:
o Set maximum-pool-size based on load testing to ensure optimal utilization of
database resources.
o Tuned connection-timeout and idle-timeout to handle variable traffic without
holding unnecessary idle connections.
3. Monitored Pool Performance:
Used Spring Boot Actuator and HikariCP’s built-in metrics to monitor connection pool
utilization and fine-tune settings further.
Results:
Reduced Latency: Average response time dropped from 1.5 seconds to 300 ms during peak
hours.
Improved Scalability: The application handled 3x more concurrent requests without
performance degradation.
Lowered Resource Usage: Database server CPU usage decreased by 40%, and memory
consumption stabilized.
Zero Downtime: The application remained stable even under heavy loads.
Impact:
This optimization not only improved user experience but also reduced operational costs by
avoiding the need to scale the database server unnecessarily. The system became a model
for other teams within the organization to follow.
1. Programming Style:
2. Ease of Use:
3. Modern Approach:
4. Purpose:
java
Copy code
@Autowired
.param(1, "Alice")
.param(2, 28)
.param(3, "Finance")
.update();
java
Copy code
.param(1, id)
.query(Map.class)
.singleResult();
java
Copy code
.param(1, newAge)
.param(2, id)
.update();
}
4. Delete (Remove a Record)
java
Copy code
.param(1, id)
.update();
This makes JdbcClient a great choice for building modern Spring Boot applications
with minimal complexity.
1. @SpringBootApplication
3. Automatically enables component scanning in the current package and its sub-packages.
Example:
@SpringBootApplication
SpringApplication.run(MyApplication.class, args);
2. @Configuration
4. Ensures that Spring manages the beans defined within the class.
Example:
@Configuration
@Bean
3. @ComponentScan
1. Enables Spring to scan for components (like @Component, @Service, @Repository, etc.)
within specified packages.
Example:
}
4. @Bean
2. The method annotated with @Bean should return an object that will be managed by Spring.
3. Supports custom initialization and destruction methods for the bean lifecycle.
Example:
@Bean
5. @Component
3. Helps implement application logic that can be reused across the project.
Example:
@Component
System.out.println("Doing something...");
6. @Autowired
2. Allows Spring to resolve and inject collaborating beans into a dependent bean.
5. Can be combined with @Qualifier to specify which bean to inject when multiple beans of
the same type exist.
Example:
@Component
@Autowired
myService.doService();
7. @Qualifier
1. Resolves ambiguity when multiple beans of the same type are available.
5. Works well in cases where there are multiple implementations of the same interface.
Example:
@Component("service1")
@Component("service2")
@Autowired
@Qualifier("service1")
private MyService myService;
8. @Controller
Example:
@Controller
@RequestMapping("/home")
return "home";
9. @Service
Example:
@Service
System.out.println("Service logic...");
}
10. @ResponseBody
1. Indicates that the return value of a method should be bound to the HTTP response body.
3. Automatically converts Java objects into JSON or XML based on the HTTP request.
Example:
@Controller
@RequestMapping("/json")
@ResponseBody
11. @RequestMapping
3. Supports additional attributes like method, headers, and params for detailed mapping.
4. Handles multiple HTTP methods like GET, POST, PUT, etc., by default.
Example:
@RequestMapping("/home")
return "home";
12. @GetMapping
Example:
@GetMapping("/users")
return userService.getAllUsers();
13. @PostMapping
2. Used for creating new resources or performing actions that modify data.
Example:
@PostMapping("/users")
userService.createUser(user);
14. @PutMapping
Example:
@PutMapping("/users/{id}")
userService.updateUser(id, user);
}
1. Purpose: Used in Spring MVC to map the body of an HTTP request to a Java object. It is
primarily used in RESTful web services to handle JSON or XML input.
2. Usage Context: Often placed in a controller method argument to indicate that the parameter
should be populated with the request body content.
3. Conversion: Automatically deserializes the request body (e.g., JSON) into a Java object using
a configured HttpMessageConverter.
4. Validation: Can be combined with validation annotations like @Valid to validate incoming
data before processing.
5. Common Use Case: Handling data from client-side POST or PUT requests in REST APIs.
Example of @RequestBody
java
Copy code
@RestController
@RequestMapping("/api/users")
@PostMapping("/create")
}
16. @Repository Annotation
1. Purpose: Marks a class as a Data Access Object (DAO) that provides CRUD operations on a
database.
4. Integration: Works closely with ORM frameworks like Hibernate or JPA for database
operations.
5. Common Use Case: Defining database query methods, typically in conjunction with
JpaRepository or CrudRepository.
Example of @Repository
java
Copy code
@Repository
17.EnableAutoConfiguration
18. EnableWebMvc
19.PropertySource
20.Value
21.ConditionalOnProperty
22.Conditional
23.Scope
24.Entity
25.Id
26.Table
27.Column
28.GeneratedValue
29.SequenceGenerator
30.Transient
31.EntityListner
32.PrePersist
33.PostPersist
34.PreUpdate
35.PostUpdate
36.PreRemove
37.PostRemove
38.OneToOne
39.OneToMany
40.ManyToMany
41.Query
42.Param
43.Transactional
17. @EnableAutoConfiguration
2. Scans Dependencies: Scans the classpath to find and configure beans related to commonly
used libraries like Hibernate, JPA, or embedded Tomcat.
4. Exclusion: Specific auto-configurations can be excluded using the exclude attribute, which
helps avoid unnecessary configurations.
java
Copy code
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
5. Advanced Use Case: Helpful for testing or when precise control over configurations is
needed.
18. @EnableWebMvc
1. Purpose: Enables Spring MVC in the application and provides complete control over its
configurations.
2. Overrides Defaults: Disables Spring Boot's auto-configuration for MVC and requires manual
configuration (e.g., for view resolvers, interceptors, etc.).
3. Use Case: Useful for advanced projects where you need to fine-tune MVC settings.
5. Example:
java
Copy code
@Configuration
@EnableWebMvc
// Custom configurations
19. @PropertySource
2. Supports Multiple Files: Multiple property files can be specified to load configurations from
different sources.
3. Custom Locations: Files can be loaded from the classpath or an external location.
4. Accessing Properties: Properties loaded via @PropertySource can be injected using @Value.
5. Example:
java
Copy code
@Configuration
@PropertySource("classpath:application.properties")
20. @Value
1. Purpose: Injects values from properties or expressions into fields, method parameters, or
constructor arguments.
4. Common Use: Retrieves configuration values from property files or environment variables.
5. Example:
java
Copy code
@Value("${app.name:Default App}")
21. @ConditionalOnProperty
2. Flexible Conditions: Can check if a property exists, has a specific value, or is missing.
4. Avoids Unnecessary Beans: Prevents creating beans when certain configurations are not
required.
5. Example:
java
Copy code
22. @Conditional
2. Custom Logic: Relies on a class implementing the Condition interface for evaluating the
condition.
5. Example:
java
Copy code
@Conditional(MyCondition.class)
public MyBean myBean() {
23. @Scope
3. Prototype Scope: Creates a new instance every time the bean is requested.
4. Request/Session Scope: Useful for web applications to scope beans to HTTP requests or
sessions.
5. Example:
java
Copy code
@Scope("prototype")
24. @Entity
3. Mapping: Requires at least one field to be annotated with @Id to identify the primary key.
5. Example:
java
Copy code
@Entity
25. @Id
5. Example:
java
Copy code
@Id
26. @Table
2. Custom Table Name: Allows specifying a table name different from the class name.
3. Schema Support: Provides the ability to define a schema for the table (e.g., schema =
"public").
5. Example:
java
Copy code
@Entity
27. @Column
4. Default Behavior: Without @Column, the field name is used as the column name.
5. Example:
java
Copy code
2. Strategies:
5. Example:
java
Copy code
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
29. @SequenceGenerator
1. Purpose: Defines a database sequence generator for generating primary key values.
2. Attributes:
5. Example:
java
Copy code
3. Use Case: Used for fields used only in business logic but not required for persistence.
4. Behavior: The field is still part of the Java object but excluded from database operations.
5. Example:
java
Copy code
@Transient
31. @EntityListeners
5. Example:
java
Copy code
@EntityListeners(AuditListener.class)
32. @PrePersist
2. Example:
java
Copy code
@PrePersist
33. @PostPersist
2. Example:
java
Copy code
@PostPersist
34. @PreUpdate
2. Example:
java
Copy code
@PreUpdate
35. @PostUpdate
2. Example:
java
Copy code
@PostUpdate
36. @PreRemove
java
Copy code
@PreRemove
37. @PostRemove
2. Example:
java
Copy code
@PostRemove
38. @OneToOne
2. Owning Side: The entity with the @JoinColumn is the owning side of the relationship.
5. Example:
java
Copy code
@OneToOne(cascade = CascadeType.ALL)
39. @OneToMany
1. Purpose: Defines a one-to-many relationship between two entities, where one entity is
related to multiple instances of another entity.
2. Mapped By: Specifies the field in the child entity that maps the relationship (inverse side).
4. Lazy Loading: Default fetch type is LAZY, meaning data is loaded only when accessed.
5. Example:
java
Copy code
40. @ManyToMany
2. Join Table: Requires a @JoinTable annotation to specify the join table and join columns.
3. Bidirectional Mapping: Both sides must reference each other for a bidirectional relationship.
5. Example:
java
Copy code
@ManyToMany
@JoinTable(
name = "student_course",
41. @Query
1. Purpose: Used in Spring Data JPA to define custom JPQL or native SQL queries.
3. Native Queries: Can execute raw SQL queries by setting nativeQuery = true.
4. Performance: Optimizes performance when complex queries are required.
5. Example:
java
Copy code
42. @Param
3. Required: Every named parameter in the query must be bound to a method parameter using
@Param.
5. Example:
java
Copy code
43. @Transactional
4. Isolation: Defines the isolation level for the transaction (e.g., READ_COMMITTED).
5. Example:
java
Copy code
@Transactional
// Transactional code
What is the best way to Inject Dependencies in spring boot.
How It Works: The @Autowired annotation is placed directly on the class fields, and Spring
injects the dependencies.
Example:
java
Copy code
@Service
@Autowired
Advantages
Drawbacks
1. Testability Issues:
o Makes unit testing harder because you cannot pass mock dependencies directly
into the object. Reflection is needed to set fields during testing.
2. Encapsulation Violation:
o Fields are injected directly, bypassing the class constructor, which can lead to
hidden dependencies.
3. Immutability:
o Dependencies are mutable since they are assigned after object creation.
Example:
java
Copy code
@Service
@Autowired
this.userRepository = userRepository;
Advantages
o Ensures all required dependencies are passed at the time of object creation.
o Makes the dependencies explicit in the constructor, improving code readability and
maintainability.
2. Immutability:
o Example:
java
Copy code
4. Null-Safety:
o Constructor injection ensures dependencies are not null, as they are required for
object creation.
5. Recommended by Spring:
Drawbacks
1. Boilerplate:
o Requires writing constructors for each class (though modern IDEs generate them
quickly).
Example:
java
Copy code
@Service
@Autowired
this.userRepository = userRepository;
Advantages
1. Optional Dependencies:
o Can be used for optional dependencies that are not required for object creation.
Drawbacks
1. Immutability:
2. Hidden Dependencies:
2. Testability:
o It makes classes easier to test without requiring additional mocking tools or
frameworks.
In Spring Boot (Spring 4.3+), if there’s only one constructor in a class, you don’t even need
to annotate it with @Autowired. Spring will automatically inject the dependencies.
java
Copy code
@Service
this.userRepository = userRepository;
1. Field Injection:
2. Setter Injection:
o Use when dependencies are truly optional and can be changed after object
creation (rare use case).
Conclusion
Use Constructor Injection as the default and best practice. It ensures clear, testable, and
maintainable code.
Avoid field injection for modern Spring projects unless dealing with legacy code.