File 6048 Oopsjunit51
File 6048 Oopsjunit51
Released in June 2003 by Rod Johnson under the Apache 2.0 license, Spring
Framework is hosted by SourceForge.
Core Spring
(IoC) and Dependency Injection (DI). These concepts are crucial for
Inversion of Control
Inversion of Control (IoC) is a design principle in the
setter methods.
@Autowired).
Dependency Injection
Dependency Injection is the main functionality provided by Spring
independent of each other and the container frees them from object creation
Suppose class One needs the object of class Two to instantiate or operate a
method, then class One is said to be dependent on class Two. Now though it
might appear okay to depend on a module on the other, in the real world, this
with Dependency Injection, which makes the code easier to test and reuse .
common functionality and the injector will instantiate the objects of required
implementation. The task of instantiating objects is done by the container
SDI, the @Autowired annotation is used along with setter methods, and the
property is set through the <property> tag in the bean configuration file.
file.
AOP
Aspect-Oriented Programming (AOP) in Spring Boot is a powerful feature
that enhances modularity by handling cross-cutting concerns such as
logging, security, and transaction management separately from business
logic.
Without AOP, these concerns would be scattered throughout the codebase,
leading to duplication and maintenance challenges. Spring AOP provides a
lightweight proxy-based approach to implementing AOP efficiently in
enterprise applications. In this article, we will explore AOP concepts, Spring
AOP implementation, and real-world examples to help you integrate AOP
into your Spring Boot projects effectively.
different classes..
its outcome.
exception.
applied.
@Autowired Annotation:
The primary way to enable autowiring is using the @Autowired annotation. It
can be applied to:
● Fields: Spring injects a bean directly into the field.
● Constructors: Spring injects beans into the constructor parameters.
● Setter Methods: Spring injects beans through setter methods.
Types of Autowiring:
byType:
Spring searches for a bean of the same type as the dependency. This is the most
common approach.
byName:
Spring searches for a bean with a name that matches the dependency's field or
parameter name.
constructor:
Spring uses the constructor to resolve dependencies.
autodetect:
Spring tries to resolve dependencies by constructor first, and if no match is found, it
tries by type.
Benefits of Autowiring:
Reduced Configuration:
Eliminates the need for explicit XML or Java configuration for dependency
injection.
Improved Readability:
Makes code cleaner and easier to understand by removing dependency wiring
details.
Increased Development Speed:
Simplifies the development process by automating dependency resolution.
Flexibility:
Allows for easy modification of dependencies without changing the wiring
configuration.
configuration class.
singleton, prototype).
files.
initialized.
injection.
prototype-scoped beans.
Example:
@Component
@Profile("developer")
public class Employee {}
● @Import: This annotation imports other configuration classes.
files.
template.
the URL.
auto-configuration mechanism.
● @ConditionalOnClass: This annotation configures a bean only if a
context.
in Spring.
asynchronously.
fixed schedule.
procedure.
in a Spring application.
MongoDB document.
document.
Bean life cycle is managed by the spring container. When we run the
program, first of all, the spring container gets started. After that, the
container creates the instance of a bean as per the request, and then
dependencies are injected. Finally, the bean is destroyed when the spring
instantiation and just after closing the spring container, then we can write
that code inside the custom init() method and the destroy() method.
The lifecycle of a Spring bean consists of the following phases, which are
listed below
● Container Started: The Spring IoC container is initialized.
the bean.
method.
used.
● Custom utility method: This could be any custom method you have
XML-based Configuration
How it works:
Bean definitions are specified in an XML file, typically named
applicationContext.xml. This file contains <bean> elements, each defining
a bean's class, properties, and dependencies.
Pros:
Centralized configuration, good for legacy projects, clear separation of
configuration from code.
Cons:
Verbose, which can be harder to maintain for complex applications, lacks compile-
time safety.
Annotation-based Configuration
● How it works: Uses annotations directly on Java classes and methods to define
beans. Key annotations include:
● @Component: Marks a class as a Spring-managed component.
● @Service, @Repository, @Controller: Specialized forms of
@Component for specific layers.
● @Bean: Used on methods within @Configuration classes to define
beans.
● @Autowired: Injects dependencies into fields, constructors, or methods.
● @Configuration: Indicates that a class provides bean definitions
● Pros: Concise, reduces boilerplate, easy to refactor, leverages compile-time
safety.
● Cons: Can be less clear for complex configurations, might require more
scanning.
Java-based Configuration
How it works:
Uses @Configuration classes and @Bean methods to define beans
programmatically. This approach allows for more complex logic and conditional
bean creation.
Pros:
Type-safe, supports refactoring, integrates well with IDEs, allows for dynamic
bean definitions.
Cons:
Can be more verbose than annotation-based configuration, might require writing
more code.
Spring Boot
Spring Boot is a Java framework that makes it easier to create and run Java
This Spring Boot Tutorial is a comprehensive guide that covers both basic
as well as professionals.
Dependency Management
Spring Boot team provides a list of dependencies to support the Spring Boot
version for its every release. You do not need to provide a version for
dependencies in the build configuration file. Spring Boot automatically
configures the dependencies version based on the release. Remember that
when you upgrade the Spring Boot version, dependencies also will upgrade
automatically.
Maven:
Gradle:
● Uses a build.gradle file for dependency management and configuration.
● Offers more flexibility and faster build times compared to Maven.
● Supports both Groovy and Kotlin for build scripts.
Dependency Management:
● While not as well-supported, Spring Boot can also work with other build systems
like Ant.
● spring-boot-antlib is a module that helps Ant create executable JARs.
However, there are some best practices followed by developers that will
help us too. You can divide your project into layers like service layer, entity
layer, repository layer,, etc. You can also divide the project into modules. For
example, the parent project has two child modules. The first module is for
the data layer and the second module is for the web layer.
2. Structure by Layer
Structure 1: By feature
In this approach, all classes pertaining to a certain feature are placed in the
same package. The structure by feature looks is shown in below example
Example
com
+- gfg
+- demo
+- MyApplication.java
|
+- customer
| +- Customer.java
| +- CustomerController.java
| +- CustomerService.java
| +- CustomerRepository.java
|
+- order
+- Order.java
+- OrderController.java
+- OrderService.java
+- OrderRepository.java
Though the above structure looks feasible and easy to locate classes by a
layer. It has few disadvantages when compared to Structure by Feature.
● Features or Modules cannot be shipped separately.
@Override
System.out.println("Executing CommandLineRunner...");
@Override
System.out.println("Executing ApplicationRunner...");
}
}
Key Differences :
Log Levels
Levels Usage
Error It is used for non-recoverable error.
authentication.
attacks.
HTTPS.
Advantages of RESTful Web Services
APIs quickly.
projects.
RestController
This annotation is used at the class level and allows the class to handle the
requests made by the client. The RestController allows the class to handle
REST API requests such as GET, POST, PUT, and DELETE by automatically
Request Mapping
In Spring Boot, @RequestMapping is a crucial annotation for mapping HTTP
requests to specific handler methods within controllers. It acts as a bridge,
connecting incoming web requests to the appropriate code that should handle
them.
PathVariable
The @PathVariable annotation is used to retrieve data from the URL path. By
defining placeholders in the request mapping URL, you can bind those
allows you to access dynamic values from the URL and use them in your
code. For example, you can extract a user ID from a URL like /users/123 and
Request Parameter
The @RequestParam annotation enables you to extract data from the query
appended to the URL after a question mark (?). With @RequestParam, you
can specify the name of the parameter to retrieve and bind it to a method
filters to your API endpoints. For instance, you can extract the value of a
By understanding and utilizing the appropriate HTTP methods, developers can build robust
and well-designed APIs that adhere to the principles of HTTP and REST. This ensures
consistency, interoperability, and efficiency in the communication between clients and
servers.
Below we will elaborate more on the most commonly used HTTP methods.
GET Method:
The GET method is one of the fundamental HTTP methods used for retrieving data from a
server. It is designed to be safe, meaning it should not modify any data on the server. When
using the GET method, the client requests a representation of a resource from the server.
Here are some key points to consider when working with the GET method in API
development:
1. Retrieving Data: The primary purpose of the GET method is to retrieve data from
the server. It is commonly used to fetch resources such as user profiles, product
information, blog articles, and more. The client sends a GET request to a specific
URL, and the server responds with the requested data.
2. Request Parameters: GET requests can include parameters in the URL to provide
additional information to the server. These parameters are appended to the URL
as query parameters, typically in the form of key-value pairs. For example, a GET
request to retrieve user information for a specific ID could look like: GET /users?
id=123. The server can use these parameters to filter or modify the returned data
accordingly.
3. Idempotence: The GET method is considered idempotent, meaning that multiple
identical GET requests should have the same outcome. It implies that making
multiple GET requests for the same resource should not result in any unintended
side effects or modifications on the server. It allows caching mechanisms to be
employed for efficient retrieval and reduces the risk of unintentional changes or
inconsistencies.
4. Response Codes: The server responds to a GET request with an appropriate
HTTP response code to indicate the success or failure of the request. The most
common response code is 200 (OK), indicating that the request was successful,
and the requested resource is returned in the response body. Other possible
response codes include 404 (Not Found) if the requested resource does not exist,
or 500 (Internal Server Error) if there was an error on the server while processing
the request.
5. Limitations: While the GET method is crucial for retrieving data, it has certain
limitations to consider:
● Data Length: GET requests have limitations on the length of the URL.
Excessive data in the URL can result in truncation, errors, or security
vulnerabilities. It is recommended to keep the data size within
reasonable limits and consider alternative methods (e.g., POST) for
large payloads.
● Security Considerations: Since GET requests expose the data in the
URL, it is important to avoid including sensitive information like
passwords or authentication tokens in the query parameters. Instead,
consider using other secure methods such as headers or request bodies
for transmitting sensitive data.
POST Method:
The POST method is one of the HTTP methods used for submitting data to be processed
by the server. Unlike the GET method, which is used for retrieving data, the POST method
is intended for data submission and can cause modifications on the server. Here are some
important points to consider when working with the POST method:
1. Submitting Data: The primary purpose of the POST method is to submit data to
the server for processing or storage. This data can be in various formats such as
form data, JSON, XML, or binary data. The POST request typically includes a
request body that contains the data being sent to the server.
2. Idempotence: Unlike the GET method, the POST method is generally considered
non-idempotent. This means that multiple identical POST requests may have
different outcomes or effects on the server. For example, submitting the same
POST request multiple times may result in the creation of multiple resources or
duplicate entries.
3. Request Headers: POST requests often include specific headers to provide
additional information about the request or the format of the data being sent. For
example, the “Content-Type” header specifies the format of the data in the
request body, such as “application/json” or “application/x-www-form-urlencoded”.
4. Response Codes: Similar to other HTTP methods, the server responds to a
POST request with an appropriate HTTP response code to indicate the success
or failure of the request. The common response code for a successful POST
request is 201 (Created), indicating that the resource has been successfully
created on the server. Other possible response codes include 200 (OK) for
general success or 400 (Bad Request) for invalid or malformed requests.
5. Limitations: While the POST method is commonly used for data submission, it
also has some limitations to consider:
● Lack of Idempotence: As mentioned earlier, the non-idempotent nature
of the POST method means that repeated identical requests may lead to
unintended side effects. It is important to design APIs in a way that
handles duplicate submissions appropriately and ensures data integrity.
● Lack of Caching: By default, POST requests are typically not cacheable.
Caching is important for improving performance and reducing the load
on the server. If caching is required for POST requests, additional
measures such as Cache-Control headers or server-side caching
strategies need to be implemented.
When using the POST method, it is crucial to ensure proper authentication, authorization,
and input validation to prevent security vulnerabilities and protect the integrity of the server
and data.
Remember to use the appropriate HTTP method based on the intended operation. While
the GET method is used for retrieving data, the POST method is suitable for submitting data
for processing or creating new resources on the server.
PUT Method:
The PUT method is an HTTP method used for updating or replacing a resource on the
server. It is idempotent, meaning that multiple identical PUT requests should have the same
outcome. Here are some important points to consider when working with the PUT method:
When using the PUT method, it is important to handle concurrency and data consistency
issues appropriately. For example, you may use optimistic locking mechanisms or
versioning to ensure that updates do not conflict with other concurrent modifications to the
resource.
Remember to use the appropriate HTTP method based on the intended operation. While
the GET method is used for retrieving data and the POST method is used for submitting
data, the PUT method is suitable for updating existing resources on the server.
DELETE Method:
The DELETE method is an HTTP method used for deleting a specified resource on the
server. It is used to remove a resource permanently from the server. Here are some
important points to consider when working with the DELETE method:
Remember to use the appropriate HTTP method based on the intended operation. While
the GET method is used for retrieving data, the POST method is used for submitting data,
the PUT method is used for updating data, the DELETE method is specifically designed for
resource deletion.