0% found this document useful (0 votes)
3 views

Spring Boot Interview Questions

The document is a comprehensive guide on Spring Boot, covering its features, advantages over traditional Spring, and key annotations. It explains the workings of Spring Boot, the importance of connection pooling, and introduces JdbcClient as a modern alternative to JdbcTemplate for database operations. Additionally, it provides best practices, configuration examples, and a case study demonstrating the optimization of database performance using connection pooling.

Uploaded by

Abhijeet Wagh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Spring Boot Interview Questions

The document is a comprehensive guide on Spring Boot, covering its features, advantages over traditional Spring, and key annotations. It explains the workings of Spring Boot, the importance of connection pooling, and introduces JdbcClient as a modern alternative to JdbcTemplate for database operations. Additionally, it provides best practices, configuration examples, and a case study demonstrating the optimization of database performance using connection pooling.

Uploaded by

Abhijeet Wagh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Spring Boot Interview Questions:

1) What is spring boot?

 java framework

 simplify conf. and setup process

 provide RAD

 Dependency management

 Solves problems by automating configurations and dependency management, embedded


server (tomcat)

2) Why Spring Boot over Spring?

Easy to use

Production ready applications: It provides many tools for production ready applications like
Actuators

(Spring boot is advanced module of spring)


3) Working of Spring Boot

- First it scans pom.xml and checks what are dependencies


- While building it downloads all jar files for dependencies
- Download and auto-configures the modules included in pom.xml
- Download only happens while building and auto-configure while running
- For web application we use spring-boot-starter-web.

4) How spring boot starts?

- Starts main method of main class


- SpringApplication.run(SpringBootWorkApplication.class,args)
- Run() is static method
- It initializes and create application context
- @SpringBootApplication is main annotation
- Covers three things @Configuration @ComponentScan and @EnableAutoConfiguration
- IMP: Annotations are interfaces
- At last run() starts application embedded web server(tomcat)
- That method returns object of application context ConfigurableApplicationContext
5) Top Spring Boot Annotations

@SpringBootApplication

1. @SpringBootApplication: combines three annotations


2. @Configuration @ComponentScan and @EnableAutoConfiguration
3. Typically places on the main class of the application
4. We can create beans in configuration class @Configuration
5. If you want to scan any other package then u can mention in @ComponentScan
and checks if there is any spring component in it if yes, the context will consider
it

@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

1. Used to automatically inject dependencies into spring managed bean


2. We don’t have to manually create object ( high coupling) we prefer loose
coupling

@Service: used to represent component containing business logic

@RestController: marks class as REST controller

1. @Controller + @ResponseBody => @RestController

@RequestMaping: used to map URLs to methods

@Repository: Mark class as DAO. Has database persistent logic


6) What are the Spring Boot Starters

1. They are pre-configured dependencies, makes easier to develop kinds of


application
2. Include all dependencies, version control and configurations to make certain
features of spring boot application functional

7) What are key dependencies of Spring Boot?

8) What is Spring-boot-starter-parents

- Provides default configuration for spring-based applications


- Manages versions of common dependencies
- Provides default compiler level as Java 1.8 and UTF-8
- Configuration for maven plugins (maven-surefire-plugin, maven-jar-
plugin) and maven-failsafe-plugin.
- Executes a repackage goal with a repackage execution id
- Resouce filtering and it configures profile specific files(dev, pre-prod
and prod)

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

11) What is thyme leaf

- Java based server-side template engine used in Java web


applications to render dynamic pages

12) What is IOC or Inversion of control?

- Usually, we were creating any object of class using new keywords.


- So, we were using this at places where we need dependency of a
class into another dependent class
- So, we were creating it manually
- So, this control of creating this all manually, we are providing this
work of creating dependencies to a container(framework) IOC
Container
- This is called an inversion of control.
13) Explain the spring bean lifecycle

- What is bean: simple plain java object


- And beans are managed by IOC container

Lifecycle means how objects are born from start to end, and how it behaves and how it ends.

1. First container gets started


2. Container creates object of bean as per request
3. Bean Dependencies are created then injected
4. Last destroyed when container closes.

If you want to use interfaces:

Implements IntializingBean, DisposableBean and we can implement methods as afterPropertiesSet()


and destroy()

Using XML (find by yourself)


14) What is Bean Factory, and what us XMLBeanFactory?

- root interface for accessing spring bean container


- This actual container initiates configures and manages beans

Now we use application context. ConfigurableApplicationContext - extends ApplicationContext 


extends ListableBeanFactory  extends BeanFactory that is XMLBeanFactory(deprecated)

15) What is difference between BeanFactory and ApplicationContext in Spring

16) What is difference between the setter and constructor injection in Spring?

- Important to know that type and order is preserved in Constructor Injection


- Constructor injection is for mandatory dependencies and Setter Is optional.

17) What are different modules in spring


18) Difference between @Autowired and @Inject 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).

19) Difference between @Bean and @Component

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

22) What is connection pooling in spring boot?

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.

Why Connection Pooling?

1. Performance Improvement: Creating a database connection is resource-intensive. Reusing


connections reduces latency and resource usage.

2. Resource Management: Limits the number of connections to prevent overloading the


database.

3. Thread Safety: Ensures that multiple threads can use database connections without
conflicts.

How Connection Pooling Works:

1. A pool of connections is created at the application startup.

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.

Connection Pooling Libraries in Spring Boot

1. HikariCP (Default): High-performance, low-latency, and lightweight.

2. Apache DBCP: Robust but slightly slower than HikariCP.

3. Tomcat JDBC: Flexible and well-integrated with Tomcat servers.

HikariCP: The Most Preferred


Why is HikariCP better?

 Performance: Optimized for speed and throughput.

 Lightweight: Consumes fewer resources.

 Built-in Metrics: Easy to monitor and tune.

 Default in Spring Boot: Simplifies configuration.

Configuring HikariCP in Spring Boot

Step 1: Add dependencies (if not already included)

xml

Copy code

<dependency>

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

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

Step 2: Configure application.properties

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

Code Example to Test Connection Pooling


java

Copy code

@RestController

public class TestController {

@Autowired

private DataSource dataSource;

@GetMapping("/test-connection-pool")

public String testConnectionPool() {

try (Connection connection = dataSource.getConnection()) {

return "Connection successful! Using: " + connection.getMetaData().getDriverName();

} catch (Exception e) {

return "Connection failed: " + e.getMessage();

Best Practices for Connection Pooling

1. Optimize Pool Size: Set maximum-pool-size based on application needs and database
capacity.

2. Minimize Idle Connections: Use minimum-idle and idle-timeout wisely.

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

Feature HikariCP Apache DBCP Tomcat JDBC

Performance ⭐⭐⭐⭐⭐ ⭐⭐⭐ ⭐⭐⭐⭐

Ease of Use ⭐⭐⭐⭐⭐ ⭐⭐⭐ ⭐⭐⭐⭐

Integration ⭐⭐⭐⭐⭐ ⭐⭐⭐ ⭐⭐⭐⭐

Monitoring ⭐⭐⭐⭐⭐ ⭐⭐⭐ ⭐⭐⭐

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.

"Optimizing Database Performance Using Connection Pooling"


Scenario:
In one of my recent projects, we developed an internal order management system that
handled a high volume of concurrent requests from various departments. The application
used Spring Boot and connected to a PostgreSQL database.

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.

Extra Tip: Add a Monitoring Twist!


You can mention that you implemented real-time monitoring using Prometheus and
visualized connection pool metrics on Grafana dashboards, ensuring quick detection of
anomalies in the pool behavior.

This story highlights:


 Your technical skills in identifying and resolving performance issues.
 Your ability to analyze metrics and fine-tune configurations.
 A quantifiable impact that aligns with business goals.
23) What is JdbcClient? How it is different from JdbcTemplate? Perform CRUD using it.

- Added in spring 6.1 version


- And in spring boot 3.2 we can get it
- It simplifies JDBC operations, more readable and easy to understand
- Has a chaining structure for operations
- jdbcClient.sql().param().query().list()

JdbcClient is a modern, functional API introduced in Spring Framework 6.1. It


simplifies database interactions, offering a more concise and declarative way to
execute SQL queries compared to the older JdbcTemplate.

How is JdbcClient Different from JdbcTemplate?

1. Programming Style:

o JdbcClient uses functional programming and method chaining for SQL


execution, making code cleaner and easier to read.

o JdbcTemplate relies on a template-based approach that often results in


more verbose code.

2. Ease of Use:

o JdbcClient simplifies parameter handling with param() methods and


supports row mapping directly.

o JdbcTemplate requires more boilerplate code for handling query


parameters and mapping results.

3. Modern Approach:

o JdbcClient is designed for developers familiar with functional


programming paradigms.

o JdbcTemplate aligns with traditional imperative programming styles.

4. Purpose:

o JdbcClient is lightweight and better suited for newer applications


needing clean code.

o JdbcTemplate is reliable and extensively used in legacy applications.

Performing CRUD Operations Using JdbcClient

Here’s how you can perform CRUD operations with JdbcClient:

1. Create (Insert a Record)

java
Copy code

@Autowired

private JdbcClient jdbcClient;

public void createRecord() {

jdbcClient.sql("INSERT INTO employees (name, age, department) VALUES (?, ?, ?)")

.param(1, "Alice")

.param(2, 28)

.param(3, "Finance")

.update();

2. Read (Fetch a Record)

java

Copy code

public Optional<Map<String, Object>> getRecordById(int id) {

return jdbcClient.sql("SELECT * FROM employees WHERE id = ?")

.param(1, id)

.query(Map.class)

.singleResult();

3. Update (Modify a Record)

java

Copy code

public void updateRecordAge(int id, int newAge) {

jdbcClient.sql("UPDATE employees SET age = ? WHERE id = ?")

.param(1, newAge)

.param(2, id)

.update();

}
4. Delete (Remove a Record)

java

Copy code

public void deleteRecord(int id) {

jdbcClient.sql("DELETE FROM employees WHERE id = ?")

.param(1, id)

.update();

Key Benefits of Using JdbcClient:

1. Conciseness: Eliminates boilerplate code.

2. Readability: Fluent API style improves code clarity.

3. Functional Programming: Supports modern paradigms and simplifies SQL parameter


binding and result mapping.

This makes JdbcClient a great choice for building modern Spring Boot applications
with minimal complexity.

Spring Boot Annotations

Resource For Notes: https://github.com/LearnCodeWithDurgesh/top-spring-boot-annotations

1. @SpringBootApplication

1. Used on the main class to indicate it’s a Spring Boot application.

2. Combines three annotations: @Configuration, @EnableAutoConfiguration, and


@ComponentScan.

3. Automatically enables component scanning in the current package and its sub-packages.

4. Simplifies the configuration process by activating default settings and configurations.

5. Custom scanning of packages can be defined using additional arguments.

Example:

@SpringBootApplication

public class MyApplication {


public static void main(String[] args) {

SpringApplication.run(MyApplication.class, args);

2. @Configuration

1. Indicates that a class declares one or more @Bean methods.

2. Defines a source of bean definitions for the Spring IoC container.

3. Acts as a replacement for traditional XML-based configuration files.

4. Ensures that Spring manages the beans defined within the class.

5. Supports externalized configuration via properties or YAML files.

Example:

@Configuration

public class AppConfig {

@Bean

public MyService myService() {

return new MyService();

3. @ComponentScan

1. Enables Spring to scan for components (like @Component, @Service, @Repository, etc.)
within specified packages.

2. By default, scans the current package and its sub-packages.

3. Custom packages can be defined using its attributes.

4. Helps modularize applications by grouping components logically.

5. Reduces the need to manually declare beans in configuration files.

Example:

@ComponentScan(basePackages = {"com.example.services", "com.example.repositories"})

public class AppConfig {

}
4. @Bean

1. Used to define a bean within a Spring-managed configuration class.

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.

4. Ideal for creating complex objects requiring specific configuration logic.

5. Beans defined with @Bean are singleton by default.

Example:

@Bean

public MyService myService() {

return new MyService();

5. @Component

1. A generic annotation used to mark a class as a Spring-managed component.

2. Automatically registers the class as a bean in the application context.

3. Helps implement application logic that can be reused across the project.

4. Simplifies bean creation without requiring manual configuration.

5. Works alongside @ComponentScan to identify classes to manage.

Example:

@Component

public class MyComponent {

public void doSomething() {

System.out.println("Doing something...");

6. @Autowired

1. Used for automatic dependency injection in Spring.

2. Allows Spring to resolve and inject collaborating beans into a dependent bean.

3. Can be applied to constructors, fields, and setter methods.


4. Eliminates the need for manual dependency wiring in XML or Java configuration.

5. Can be combined with @Qualifier to specify which bean to inject when multiple beans of
the same type exist.

Example:

@Component

public class MyController {

@Autowired

private MyService myService;

public void performAction() {

myService.doService();

7. @Qualifier

1. Resolves ambiguity when multiple beans of the same type are available.

2. Used alongside @Autowired to specify which bean to inject.

3. Requires the bean to be explicitly named using @Component("name") or similar


annotations.

4. Helps maintain clean and understandable dependency injection configurations.

5. Works well in cases where there are multiple implementations of the same interface.

Example:

@Component("service1")

public class Service1 implements MyService {

@Component("service2")

public class Service2 implements MyService {

@Autowired

@Qualifier("service1")
private MyService myService;

8. @Controller

1. Marks a class as a Spring MVC controller.

2. Handles incoming web requests and maps them to specific methods.

3. Works in conjunction with view resolvers to render views.

4. Methods can return a string representing the view name.

5. Simplifies the implementation of web endpoints for the application.

Example:

@Controller

public class MyController {

@RequestMapping("/home")

public String home() {

return "home";

9. @Service

1. Specialization of @Component, used to define service layer beans.

2. Focuses on encapsulating business logic and service-related tasks.

3. Makes the code more readable by clearly distinguishing service components.

4. Helps modularize application logic.

5. Automatically registers the class as a Spring bean.

Example:

@Service

public class MyService {

public void doService() {

System.out.println("Service logic...");

}
10. @ResponseBody

1. Indicates that the return value of a method should be bound to the HTTP response body.

2. Typically used in RESTful web services.

3. Automatically converts Java objects into JSON or XML based on the HTTP request.

4. Removes the need to explicitly use HttpServletResponse for writing responses.

5. Often used with @Controller or @RestController.

Example:

@Controller

public class MyController {

@RequestMapping("/json")

@ResponseBody

public String jsonResponse() {

return "{\"message\": \"Hello World\"}";

11. @RequestMapping

1. Maps web requests to specific handler classes or methods.

2. Can be used at the class or method level.

3. Supports additional attributes like method, headers, and params for detailed mapping.

4. Handles multiple HTTP methods like GET, POST, PUT, etc., by default.

5. Provides a flexible mechanism for routing requests.

Example:

@RequestMapping("/home")

public String home() {

return "home";

12. @GetMapping

1. A specialized version of @RequestMapping for handling HTTP GET requests.

2. Simplifies mapping of GET requests to handler methods.


3. Commonly used for fetching resources in RESTful services.

4. Supports attributes like headers, params, and consumes.

5. Encourages cleaner and more descriptive code.

Example:

@GetMapping("/users")

public List<User> getUsers() {

return userService.getAllUsers();

13. @PostMapping

1. A shortcut annotation for mapping HTTP POST requests.

2. Used for creating new resources or performing actions that modify data.

3. Supports additional attributes like consumes and produces.

4. Simplifies RESTful service development.

5. Automatically binds request data to method parameters if annotated with @RequestBody.

Example:

@PostMapping("/users")

public void createUser(@RequestBody User user) {

userService.createUser(user);

14. @PutMapping

1. Maps HTTP PUT requests to specific handler methods.

2. Commonly used for updating existing resources in REST APIs.

3. Similar to @PostMapping but follows HTTP standards for resource updates.

4. Can include additional attributes like consumes and produces.

5. Often used with @PathVariable for resource identification.

Example:

@PutMapping("/users/{id}")

public void updateUser(@PathVariable int id, @RequestBody User user) {

userService.updateUser(id, user);
}

15. @RequestBody Annotation

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

public class UserController {

@PostMapping("/create")

public ResponseEntity<String> createUser(@RequestBody User user) {

// Logic to save the user

return ResponseEntity.ok("User created successfully!");

// Sample User class

public class User {

private String name;

private int age;

// Getters and Setters

}
16. @Repository Annotation

1. Purpose: Marks a class as a Data Access Object (DAO) that provides CRUD operations on a
database.

2. Spring Context: It is a specialization of the @Component annotation, allowing Spring to


detect and register the class as a Spring bean.

3. Exception Translation: Automatically translates persistence-related exceptions into Spring's


DataAccessException.

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

public interface UserRepository extends JpaRepository<User, Long> {

// Custom query to find a user by name

Optional<User> findByName(String name);

17.EnableAutoConfiguration

- also expain exclude

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

1. Purpose: Enables Spring Boot's auto-configuration feature, which automatically configures


beans and settings based on the application classpath and defined properties.

2. Scans Dependencies: Scans the classpath to find and configure beans related to commonly
used libraries like Hibernate, JPA, or embedded Tomcat.

3. Combination: Included in @SpringBootApplication, so it is often not used explicitly.

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.

4. Integration: Works in conjunction with WebMvcConfigurer to customize behavior.

5. Example:

java

Copy code

@Configuration

@EnableWebMvc

public class WebConfig implements WebMvcConfigurer {

// Custom configurations

19. @PropertySource

1. Purpose: Loads a property file into the Spring Environment.

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

public class AppConfig {}

20. @Value

1. Purpose: Injects values from properties or expressions into fields, method parameters, or
constructor arguments.

2. Expressions: Can evaluate simple SpEL (Spring Expression Language) expressions.


3. Fallback: Supports default values if the property is missing.

4. Common Use: Retrieves configuration values from property files or environment variables.

5. Example:

java

Copy code

@Value("${app.name:Default App}")

private String appName;

21. @ConditionalOnProperty

1. Purpose: Enables bean creation based on a property’s existence or value.

2. Flexible Conditions: Can check if a property exists, has a specific value, or is missing.

3. Configuration Toggle: Often used to enable or disable features conditionally.

4. Avoids Unnecessary Beans: Prevents creating beans when certain configurations are not
required.

5. Example:

java

Copy code

@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")

public MyFeature myFeature() {

return new MyFeature();

22. @Conditional

1. Purpose: Specifies a custom condition for bean registration.

2. Custom Logic: Relies on a class implementing the Condition interface for evaluating the
condition.

3. Advanced Use: Enables fine-grained control over bean instantiation.

4. Common Use Case: Loading environment-specific beans.

5. Example:

java

Copy code

@Conditional(MyCondition.class)
public MyBean myBean() {

return new MyBean();

23. @Scope

1. Purpose: Defines the scope of a Spring bean (e.g., singleton, prototype).

2. Default Scope: Beans are singleton by default in Spring.

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

public MyBean myBean() {

return new MyBean();

24. @Entity

1. Purpose: Marks a class as a JPA entity, representing a database table.

2. Integration: Works with ORM tools like Hibernate.

3. Mapping: Requires at least one field to be annotated with @Id to identify the primary key.

4. Lifecycle: Enables entity lifecycle callbacks (e.g., @PrePersist, @PostRemove).

5. Example:

java

Copy code

@Entity

public class User {}

25. @Id

1. Purpose: Specifies the primary key for a JPA entity.


2. Required: Each @Entity must have one @Id field.

3. Mapping: Can be combined with @GeneratedValue to auto-generate values.

4. Support for Composite Keys: Can be used with @EmbeddedId or @IdClass.

5. Example:

java

Copy code

@Id

private Long id;

26. @Table

1. Purpose: Maps a JPA entity to a specific table in the database.

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").

4. Unique Constraints: Enables defining unique constraints on table columns.

5. Example:

java

Copy code

@Entity

@Table(name = "users", schema = "public", uniqueConstraints = @UniqueConstraint(columnNames


= "email"))

public class User {}

27. @Column

1. Purpose: Maps a class field to a specific column in the database table.

2. Custom Column Name: Allows naming the column explicitly.

3. Attributes: Provides options like length, nullable, unique, etc.

4. Default Behavior: Without @Column, the field name is used as the column name.

5. Example:

java

Copy code

@Column(name = "email", nullable = false, unique = true, length = 100)

private String email;


28. @GeneratedValue

1. Purpose: Specifies how the primary key value is generated.

2. Strategies:

o AUTO: Let the persistence provider decide the generation strategy.

o IDENTITY: Relies on the database's identity column.

o SEQUENCE: Uses a database sequence.

o TABLE: Utilizes a table-based sequence.

3. Primary Key: Typically used with the @Id annotation.

4. Common Use: Simplifies primary key generation for entities.

5. Example:

java

Copy code

@Id

@GeneratedValue(strategy = GenerationType.SEQUENCE)

private Long id;

29. @SequenceGenerator

1. Purpose: Defines a database sequence generator for generating primary key values.

2. Attributes:

o name: Logical name for the sequence generator.

o sequenceName: Database sequence name.

o initialValue and allocationSize: Configure sequence properties.

3. Integration: Works with @GeneratedValue(strategy = GenerationType.SEQUENCE).

4. Use Case: Efficient key generation in databases supporting sequences.

5. Example:

java

Copy code

@SequenceGenerator(name = "user_seq", sequenceName = "user_sequence", allocationSize = 1)

@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")

private Long id;


30. @Transient

1. Purpose: Marks a field to be ignored by the persistence framework (JPA).

2. Transient Fields: These fields are not persisted to the database.

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

private String temporaryData;

31. @EntityListeners

1. Purpose: Specifies callback listeners for an entity’s lifecycle events.

2. Lifecycle Events: Supports events like @PrePersist, @PostPersist, @PreUpdate, etc.

3. Class Reference: Takes the listener class as a parameter.

4. Use Case: Encapsulates lifecycle logic in separate listener classes.

5. Example:

java

Copy code

@EntityListeners(AuditListener.class)

public class User {}

32-37. JPA Callbacks Annotations

32. @PrePersist

1. Executes logic before an entity is persisted.

2. Example:

java

Copy code

@PrePersist

public void setCreationTimestamp() {


this.createdAt = new Date();

33. @PostPersist

1. Executes logic after an entity is persisted.

2. Example:

java

Copy code

@PostPersist

public void logPersist() {

System.out.println("Entity persisted: " + this);

34. @PreUpdate

1. Executes logic before an entity is updated.

2. Example:

java

Copy code

@PreUpdate

public void setUpdateTimestamp() {

this.updatedAt = new Date();

35. @PostUpdate

1. Executes logic after an entity is updated.

2. Example:

java

Copy code

@PostUpdate

public void logUpdate() {

System.out.println("Entity updated: " + this);

36. @PreRemove

1. Executes logic before an entity is removed.


2. Example:

java

Copy code

@PreRemove

public void logRemove() {

System.out.println("Entity about to be removed: " + this);

37. @PostRemove

1. Executes logic after an entity is removed.

2. Example:

java

Copy code

@PostRemove

public void logRemoval() {

System.out.println("Entity removed: " + this);

38. @OneToOne

1. Purpose: Defines a one-to-one relationship between two entities.

2. Owning Side: The entity with the @JoinColumn is the owning side of the relationship.

3. Optional: Can specify whether the relationship is optional.

4. Cascade: Supports cascading operations like persist or remove.

5. Example:

java

Copy code

@OneToOne(cascade = CascadeType.ALL)

@JoinColumn(name = "address_id", referencedColumnName = "id")

private Address address;

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

3. Cascade: Supports cascading operations (e.g., CascadeType.ALL) for related entities.

4. Lazy Loading: Default fetch type is LAZY, meaning data is loaded only when accessed.

5. Example:

java

Copy code

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)

private List<Order> orders;

40. @ManyToMany

1. Purpose: Defines a many-to-many relationship between two entities.

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.

4. Cascade: Supports cascading operations to maintain relational integrity.

5. Example:

java

Copy code

@ManyToMany

@JoinTable(

name = "student_course",

joinColumns = @JoinColumn(name = "student_id"),

inverseJoinColumns = @JoinColumn(name = "course_id")

private Set<Course> courses;

41. @Query

1. Purpose: Used in Spring Data JPA to define custom JPQL or native SQL queries.

2. Parameters: Supports named and positional parameters.

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

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

User findByEmail(@Param("email") String email);

42. @Param

1. Purpose: Maps method parameters in repository methods to named placeholders in


@Query.

2. Supports JPQL: Works with JPQL and native queries.

3. Required: Every named parameter in the query must be bound to a method parameter using
@Param.

4. Flexibility: Helps in dynamically building queries with clear parameter names.

5. Example:

java

Copy code

@Query("SELECT u FROM User u WHERE u.name = :name")

User findByName(@Param("name") String name);

43. @Transactional

1. Purpose: Manages transaction boundaries for methods or classes.

2. Rollback: Automatically rolls back the transaction if an exception occurs.

3. Propagation: Controls how transactions should propagate (e.g., REQUIRED, REQUIRES_NEW).

4. Isolation: Defines the isolation level for the transaction (e.g., READ_COMMITTED).

5. Example:

java

Copy code

@Transactional

public void performTransaction() {

// Transactional code
What is the best way to Inject Dependencies in spring boot.

1. Field Injection (@Autowired on Fields)

 How It Works: The @Autowired annotation is placed directly on the class fields, and Spring
injects the dependencies.

 Example:

java

Copy code

@Service

public class UserService {

@Autowired

private UserRepository userRepository;

Advantages

1. Simplicity: Easy to write and understand for small applications.

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.

2. Constructor Injection (@Autowired on Constructor or Without Annotation in Modern Spring)

 How It Works: The @Autowired annotation is applied to the constructor, or it can be


omitted if there is only one constructor, as Spring automatically detects it.

 Example:
java

Copy code

@Service

public class UserService {

private final UserRepository userRepository;

@Autowired

public UserService(UserRepository userRepository) {

this.userRepository = userRepository;

Advantages

1. Mandatory Dependency Declaration:

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 Dependencies are final, ensuring they cannot be changed after initialization.

3. Better for Testing:

o Allows injecting mock dependencies directly during unit testing.

o Example:

java

Copy code

UserService userService = new UserService(mockUserRepository);

4. Null-Safety:

o Constructor injection ensures dependencies are not null, as they are required for
object creation.

5. Recommended by Spring:

o Constructor injection is preferred in modern Spring because it aligns with the


principles of Dependency Injection (DI) and Inversion of Control (IoC).

Drawbacks

1. Boilerplate:
o Requires writing constructors for each class (though modern IDEs generate them
quickly).

3. Setter Injection (@Autowired on Setters)

 How It Works: Dependencies are injected via setter methods.

 Example:

java

Copy code

@Service

public class UserService {

private UserRepository userRepository;

@Autowired

public void setUserRepository(UserRepository userRepository) {

this.userRepository = userRepository;

Advantages

1. Optional Dependencies:

o Can be used for optional dependencies that are not required for object creation.

Drawbacks

1. Immutability:

o Like field injection, dependencies are mutable after object creation.

2. Hidden Dependencies:

o Makes dependencies less explicit, reducing code clarity.

Why Constructor Injection is Best

1. Aligns with Best Practices:

o Constructor injection is recommended in modern frameworks like Spring because


it adheres to the principles of immutability and clear dependency management.

2. Testability:
o It makes classes easier to test without requiring additional mocking tools or
frameworks.

3. Enforces Dependency Contracts:

o Ensures the class cannot be instantiated without its required dependencies.

Modern Spring Boot Default Behavior

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

Example without @Autowired:

java

Copy code

@Service

public class UserService {

private final UserRepository userRepository;

public UserService(UserRepository userRepository) {

this.userRepository = userRepository;

When to Use Other Methods

1. Field Injection:

o Only for legacy codebases or very simple applications.

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.

 Use setter injection sparingly for optional dependencies.

You might also like