Oops 5
Oops 5
Spring Core
→ Spring is a lightweight application development framework for enterprise JAVA.
→ It is a complement of J2EE, JSE technology.
→ Spring is a special software that provide abstraction on existing technology and simplifies the application
development process.
→ Spring framework is a source JAVA platform, it was initially written by Rod Johnson and was first
released under Apache 2.0 in June 2003.
→ Spring framework is a special software, built technology having the ability to generate common logic at
the application dynamically.
1. Inversion of Control(IoC): The core principle of the Spring framework, is IoC, which allows the framework
to manage creation and lifecycle of objects.
2. Aspect-Oriented Programming(AOP): AOP enables modularization of concerns such as logging,
transaction management, security, and caching.
3. Spring Container: It manages the creation, configuration, and lifecycle of objects(beans)
4. Spring MVC: Spring MVC is a web framework built on top of the Spring framework, providing a robust and
flexible MVC(Model-ViewController) architecture.
5. Data access and integration: Spring provides powerful abstractions and integration for working with
various data access technologies.
6. Security: Spring security is a highly flexible and customizable security framework.
7. Testability and test integration: The Spring framework promotes testability by supporting integration
testing and providing mock objects and testing utilities.
1. Predefined Templates: Spring framework provides templates for JDBC, Hibernate, JPA technologies. So
there is no need to write too much code. It hides the basic steps of these technologies.
2. Loose Coupling: The Spring applications are loosely coupled because of dependency injection.
3. Easy to test: The dependency injection makes easier to test the application. The EJB or Struts
application require server to run the application but Spring framework does not require server.
4. Lightweight: Spring framework is lightweight because of its POJO implementation. The Spring
framework does not force the programmer to inherit any class or implement any interface.
5. Fast development: The dependency injection feature of Spring framework and it support to various
frameworks makes the easy development of JavaEE application.
Dependency Injection
→ Dependency Injection (DI) is a design pattern that removes the dependency from the programming code
so that it can be easy to manage and test the application.
→ Dependency Injection makes our programming code loosely coupled.
1. Setter Dependency Injection (SDI): This is the simpler of the two DI methods. In this, the DI will be
injected with the help of setter and/or getter methods. Now to set the DI as SDI in the bean, it is done
through the bean-configuration file For this, the property to be set with the SDI is declared under
the <property> tag in the bean-config file.
2. Constructor Dependency Injection (CDI): In this, the DI will be injected with the help of contructors. Now
to set the DI as CDI in bean, it is done through the bean-configuration file For this, the property to be set
with the CDI is declared under the <constructor-arg> tag in the bean-config file.
1. Loose Coupling: Objects are not directly dependent on their dependencies, making them easier to test,
reuse, and maintain.
2. Improved Testability: You can easily inject mock dependencies during testing to isolate components.
3. Increased Flexibility: You can change the implementation of dependencies without modifying the
dependent classes.
Page 1
Page 2
Setter DI Constructor DI
Poor readability as it adds a lot of boiler plate Good readability as it is separately present in the
codes in the application. code.
The bean must include getter and setter The bean class must declare a matching
methods for the properties. constructor with arguments. Otherwise,
BeanCreationException will be thrown.
Requires addition of @Autowired annotation, Best in the case of loose coupling with the DI
above the setter in the code and hence, it container as it is not even required to add
increases the coupling between the class and @Autowired annotation in the code.(Implicit
the DI container. constructor injections for single constructor
scenarios after spring 4.0)
Circular dependencies or partial dependencies No scope for circular or partial dependency
result with Setter DI because object creation because dependencies are resolved before object
happens before the injections. creation itself.
Preferred option when properties are less and Preferred option when properties on the bean
mutable objects can be created. are more and immutable objects (eg: financial
processes) are important for application.
Advantages:-
1. Decoupling: Promotes loose coupling between components, making the code more modular.
2. Configuration Management: Centralized management of application configuration through XML,
annotations, or Java classes.
3. Improved Testability: Easier unit testing by allowing dependencies to be mocked or stubbed out.
4. Lifecycle Management: Manages the entire lifecycle of beans, including creation, initialization, and
destruction.
5. Consistency and Uniformity: Ensures consistent object management across the application.
6. AOP Support: Integrates with Spring’s AOP capabilities for separating cross-cutting concerns.
7. Scalability and Maintainability: Promotes a scalable and maintainable architecture by enabling modular
design.
8. Dependency Injection: Simplifies dependency management with support for various types of injection.
9. Reuse and Composability: Enhances component reusability and composability across different parts of
the application.
10. Reduced Boilerplate Code: Minimizes boilerplate code by handling dependency creation and wiring.
Page 3
Aspect Oriented Programming(AOP)
→ AOP is defined as the breaking of code into different modules where the aspect is the key unit of
modularity.
→ AOP addresses cross-cutting concerns in an application.
→ Cross-cutting concerns are functionalities that cut across multiple modules or components, such as
logging, caching, authentication, and transaction management.
→ AOP provides a modular approach to separate and manage these concerns.
→ This helps in promoting code modularity, reusability, and maintainability.
→ In the Spring framework, AOP is seamlessly integrated and provides robust support for aspect-
oriented programming.
→ AOP in Spring is primarily based on proxy-based AOP and is implemented using runtime proxies.
1. Aspect: An aspect is a modular unit of cross-cutting functionality that encapsulates a concern, such as
logging or security.
2. Join point: A join point represents a specific point in the execution of a program, typically corresponding to
method invocations or exception handling.
3. Pointcut: A pointcut is a predicate that selects join points, defining the specific points in the code where
advice should be applied.
4. Advice: Advice is the code that runs at a particular join point. It represents the behavior associated with a
cross-cutting concern.
5. Aspect configuration: Aspect configuration defines how the aspect is applied to the target objects and
specifies the pointcuts and advice to be executed.
// MessageService.java
public interface MessageService {
void sendMessage(String message);
}
// EmailService.java
import org.springframework.stereotype.Component;
@Component
public class EmailService implements MessageService {
@Override
public void sendMessage(String message) {
System.out.println("Email sent: " + message);
}
}
// MessageProcessor.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MessageProcessor {
private final MessageService messageService;
@Autowired // Constructor injection
public MessageProcessor(MessageService messageService) {
this.messageService = messageService;
}
public void processMessage(String message) {
messageService.sendMessage(message);
}
// MainApp.java (example usage)
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new
AnnotationConfigApplicationContext(MainConfig.class);
MessageProcessor processor = context.getBean(MessageProcessor.class)
processor.processMessage("Hello, Spring!");
((AnnotationConfigApplicationContext) context).close();
}
}
Page 4
Bean Scope
→ In Spring Framework, the concept of "bean scope" determines how Spring manages and creates
instances of beans. Each bean represents an object managed by Spring's IoC container.
→ The bean scope defines the lifecycle and visibility of these bean instances within the Spring context.
→ Choosing the appropriate scope depends on the specific requirements of your application.
→ Singleton scope is the default and most commonly used, but prototype, request, session, and global
session scopes provide flexibility for managing different types of state and lifecycle management in
Spring applications
1. Singleton Scope:-
- When a bean is defined with singleton scope (`@Scope("singleton")` or by default), Spring IoC container
creates a single instance of that bean per container.
- This single instance is shared across the entire Spring application context, so every time the application
requests that bean, it gets the same instance.
- Useful for stateless beans where you want a single instance to be reused throughout the application.
Example:
java
@Component
@Scope("singleton")
public class SingletonBean {
// Bean definition
}
2. Prototype Scope:-
- Beans with prototype scope (`@Scope("prototype")`) are created each time they are requested from the
Spring container.
- Unlike singleton beans, which are reused, prototype beans create a new instance every time they are
injected or retrieved from the Spring context.
- Useful for stateful beans or when you want to control the lifecycle of each instance separately.
Example:
java
@Component
@Scope("prototype")
public class PrototypeBean {
// Bean definition
}
3. Request Scope:
- Request scope (`@Scope("request")`) is specific to web applications and associates a single instance of a
bean with each HTTP request.
- The bean instance is created for each new HTTP request and is destroyed once the request is completed.
- Useful when you need to maintain state or data specific to each user request.
Example:
java
@Component
@Scope("request")
public class RequestScopedBean {
// Bean definition
}
4. Session Scope:-
- Session scope (`@Scope("session")`) is similar to request scope but ties the bean's lifecycle to an HTTP
session.
- Each HTTP session gets its own instance of the bean, which remains throughout the session and is
destroyed when the session ends.
- Useful for maintaining user-specific data across multiple requests within the same session.
Page 5
Example:
java
@Component
@Scope("session")
public class SessionScopedBean {
// Bean definition
}
Example:
java
@Component
@Scope("globalSession")
public class GlobalSessionScopedBean {
// Bean definition
}
Difference between two IoC Containers
BeanFactory ApplicationContext
It is a fundamental container that provides the It is an advanced container that extends the
basic functionality for managing beans. BeanFactory that provides all basic functionality and
adds some advanced features.
It is suitable to build standalone applications. It is suitable to build Web applications, integration
with AOP modules, ORM and distributed
applications.
It supports only Singleton and Prototype bean It supports all types of bean scopes such as
scopes. Singleton, Prototype, Request, Session etc.
It does not support Annotations. In Bean It supports Annotation based configuration in Bean
Autowiring, we need to configure the properties Autowiring.
in XML file only.
This interface does not provides messaging ApplicationContext interface extends
(i18n or internationalization) functionality. MessageSource interface, thus it provides
messaging (i18n or internationalization)
functionality.
BeanFactory does not support Event publication Event handling in the ApplicationContext is provided
functionality. through the ApplicationEvent class and
ApplicationListener interface.
In BeanFactory, we need to manually register The ApplicationContext automatically registers
BeanPostProcessors and BeanFactoryPostProcessor and BeanPostProcessor
BeanFactoryPostProcessors. at startup.
BeanFactory will create a bean object when the ApplicationContext loads all the beans and creates
getBean() method is called thus making it Lazy objects at the time of startup only thus making it
initialization. Eager initialization.
BeanFactory interface provides basic features ApplicationContext provides all the basic features
only thus requires less memory. For standalone and advanced features, including several that are
applications where the basic features are geared towards enterprise applications thus
enough and when memory consumption is requires more memory.
critical, we can use BeanFactory.
WebSocket
→ WebSocket in Spring is a protocol that provides full-duplex communication channels over a single, long-
lived connection between a client and a server.
→ It facilitates real-time communication by allowing both the client and server to send and receive
messages simultaneously.
Page 6
How WebSocket Works in Spring:
1. Initial HTTP Handshake: A WebSocket connection starts with an HTTP handshake. If successful, the
connection is upgraded from HTTP to WebSocket.
2. Full-Duplex Communication: Once the connection is established, both client and server can send and
receive messages independently in real-time.
Key Benefits:
- Low Latency: Enables instant data exchange, suitable for applications needing real-time updates (e.g., chat
apps, live notifications).
- Efficiency: Reduces overhead by maintaining a single connection, unlike HTTP where a new connection is
made for each request/response.
Example Setup:
Controller: Handles WebSocket connections and messages.
java
@Controller
public class WebSocketController {
@MessageMapping("/message")
@SendTo("/topic/response")
public String processMessage(String message) {
return "Received: " + message;
}
}
Auto-wiring
Auto-wiring in Spring:
→ Auto-wiring in Spring is a feature that automatically resolves dependencies between beans without the
need for explicit configuration.
→ It simplifies bean configuration by automatically connecting beans based on their types, eliminating the
need for manual wiring.
Annotations
→ Spring boot annotation is a form of metadata that provides data about a program.
→ Annotations are used to provide supplemental information about a program. It is not a part of the
application that we develop.
→ It does not have a direct effect on the operation of the code they annotate. It does not change the action
of the compiled program.
Page 7
4. @ComponentScan: It is used when we want to scan a package for beans. It is used with the
annotation @Configuration. We can also specify the base packages to scan for Spring Components.
5. @Bean: It is a method-level annotation. It is an alternative of XML tag. It tells the method to produce
a bean to be managed by spring container.
Page 8
Bean Configurations Styles
1. In Spring Boot, choosing a build system is an important task. So, Maven or Gradle are good build system as
they provide a good support for dependency management.
2. Spring Boot team provides a list of dependencies to support the Spring Boot version for its every release.
3. 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.
4. When you upgrade the Spring Boot version, dependencies will upgrade automatically.
Maven dependency: For Maven configuration, we should inherit the Spring Boot Starter parent project to manage
the Spring Boot Starters dependencies. For this, simply we can inherit the starter parent in our pom.xml file as
shown below.
Page 9
<parent>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter parent</artifactId>
<version>1.5.8.RELEASE</version>
<parent>
We should specify the version number for Spring Boot Parent Starter dependency. Then for other starter
dependencies, we do not need to specify the Spring Boot version number. Observe the code given below:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
Gradle dependency: We can import the Spring Boot Starters dependencies directly into build.gradle file. We do
not need Spring Boot start Parent dependency like Maven or Gradle. Observe the code given below:
Buildscript {
ext {
spring BootVersion="1.5.8.RELEASE"
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-bo gradleplugin:$(springBootVersion)")
}
}
Similarly, in Gradle, we need not specify the Spring Boot version number for dependencies. Spring Boot
automatically configures the dependency based on the version.
dependencies {
compile('org.springframework.boot:spring-boot-starter-web")
}
Presentation Layer: The presentation layer handles the HTTP requests, translates the JSON parameter to
object, and authenticates the request, and transfer it to the business layer. In short, it consists of views.
Business Layer: The business layer handles all the business logic. It consists of service classes and uses
services provided by data access layers. It also performs authorization and validation.
Persistence Layer: The persistence layer contains all the storage logic and translates business objects from
and to database rows.
Database Layer: In the database layer, CRUD (create, retrieve, update, delete) operations are performed.
Page 10
Spring Boot Code Structure
→ In a Spring Boot application, the code is typically structured in following certain conventions and best
practices. The recommended structure organizes the code in a modular and maintainable way.
Following is a typical structure for a Spring Boot application:
1. Main application class: The application starts with a main class annotated with @SpringBootApplication.
This class serves as the entry point of the application and initializes the Spring Boot environment.
2. Controller classes: These classes are responsible for handling incoming requests and returning
appropriate responses. They are typically annotated with @RestController or @Controller.
3. Service classes: Service classes contain the business logic of the application. They handle complex
operations and are often annotated with @Service.
4. Repository/DAO classes: These classes interact with the database or other data sources. They are
responsible for data retrieval, storage, and manipulation. They are typically annotated with @Repository
or @Component.
5. Model/Entity classes: Model or entity classes represent the data structure of the application. They define
the structure and relationships of the objects used in the application.
6. Configuration classes: Configuration classes provide additional configuration and customization options
for the application. They can include beans, database configuration, security configuration, etc. These
classes are often annotated with @Configuration.
7. Utility classes: Utility classes contain helper methods and utility functions that can be used across
different parts of the application. They provide common functionality and reusable code snippets.
8. Resource files: Resource files include static resources such as HTML, CSS, JavaScript, and other files
required for the application. They are typically stored in the src/main/resources directory.
9. Test classes: Test classes contain unit tests, integration tests, and other tests to ensure the correctness
of the application. They are stored in a separate directory, usually src/test/java.
Application Runner
The ApplicationRunner interface in Spring Boot provides a way to execute code after the application context
is initialized and before Spring Boot starts servicing incoming requests
Command-Line Runner
Similar to ApplicationRunner, CommandLineRunner is an alternative interface that provides a run method
with an array of String arguments. These arguments are passed directly to the application when it is started
from the command line.
//Command-line Runner
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class MyCommandLineRunner implements
CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// Code to execute on application startup
System.out.println("CommandLineRunner is
running...");
Application Runner }}
Loggers
In Spring Boot applications, logging is an essential aspect of monitoring and debugging. Spring Boot integrates
with popular logging frameworks like Logback, Log4j2, and Java Util Logging (JUL). Here’s a guide on how to
use logging in a Spring Boot application with an example using Logback.
Steps to add Logger in Springboot App
Step1: Add dependency in POM.XML File
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.13</version>
</dependency>
Page 11
REST API
→ REpresentational State Transfer (REST) is a software architectural style that developers apply to web
application programming interfaces (APIs).
→ REST APIs are the most common APIs used across the web today because the REST pattern provides
simple, uniform interfaces. These can be used to make data, content, algorithms, media, and other
digital resources available through web URLs, so that they can be consumed within web, mobile, and
device applications.
→ REST stands for Representational State Transfer. The main goal of RESTful web services is to make web
services more effective.
→ RESTful web services try to define services using the different concepts that are already present in
HTTP.
→ REST is an architectural approach, not a protocol. It does not define the standard message exchange
format.
→ We can build REST services with both XML and JSON, JSON is more popular format with REST.
→ The key abstraction is a resource in REST. A resource can be anything. It can be accessed through a
Uniform Resource Identifier (URI).
→ For example: The resource has representations like XML, HTML, and JSON. The current state capture by
representational resource. When we request a resource, we provide the representation of the resource.
@RestController
A REST controller in Spring Boot is used to handle HTTP requests and return HTTP responses. It allows
you to create RESTful web services easily.
Key Components
1. Annotations:
○ @RestController: Indicates that the class is a REST controller.
○ @RequestMapping or @GetMapping, @PostMapping, etc.: Map HTTP requests to specific
methods.
2. Methods:
○ Methods inside the controller handle different HTTP methods like GET, POST, PUT, DELETE.
Page 12
Example:
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class MyRestController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
Request Mapping
Example:-
@RequestMapping(value = "/products")
- This will map HTTP requests to `/products` to a specific handler method in the controller.
Request Body: The `@RequestBody` annotation is used to define the request body content type.
Example:-
public ResponseEntity<Object> createProduct(@RequestBody Product product) {
// Method implementation
}
Path Variable: The `@PathVariable` annotation is used to define the custom or dynamic request URI. The
path variable in request URI is defined as curly braces `{}`.
Example:-
public ResponseEntity<Object> updateProduct(@PathVariable("id") String id) {
// Method implementation
}
Request Parameter: The `@RequestParam` annotation is used to read the request parameters from the
request URL. By default, it is a required parameter. You can also define default values for request
parameters.
Example:-
public ResponseEntity<Object> getProduct(@RequestParam(value = "name", required = false, defaultValue =
"Honey") String name) {
// Method implementation
}
Page 13
GET API: The default HTTP request method is GET. This method does not require any Request Body. You can
send request parameters and path variables to define the custom or dynamic URL.
POST API: The HTTP POST request is used to create a resource. This method contains the Request Body. We
can send request parameters and path variables to define the custom or dynamic URL.
PUT API: The HTTP PUT request is used to update the existing resource. This method contains a Request
Body. We can send request parameters and path variables to define the custom or dynamic URL.
DELETE API: The HTTP DELETE request is used to delete the existing resource. This method does not contain
any Request Body. We can send request parameters and path variables to define the custom or dynamic
URL.
POST
GET @PostMapping("/products")
public Product
@GetMapping("/products") createProduct(@RequestBody
public List<Product> getAllProducts() { Product product) {
return productService.findAll(); return
} productService.save(product);
}
PUT
@PutMapping("/products/{id}")
public Product updateProduct(@PathVariable Long id, @RequestBody Product product) {
return productService.update(id, product);
}
DELETE
@DeleteMapping("/products/{id}")
public void deleteProduct(@PathVariable Long id) {
productService.delete(id);
}
Following is a general guide on how to use Spring Boot to build web applications:
1. Setup project: Start by creating a new Spring Boot project using either Spring Initializr or your
preferred integrated development environment (IDE).
2. Dependencies: In your project's build configuration include the necessary dependencies for building
web applications. Common dependencies include spring-boot-starter-web for basic web functionality,
and additional dependencies for templating engines and database access.
3. Create controllers: Create classes annotated with @Controller or @RestController to handle incoming
HTTP requests. Use @RequestMapping and related annotations to define mappings between URLs and
controller methods.
4. View templates: If your application requires rendering dynamic content, include the corresponding
Spring Boot starter dependency. create template files in the designated directory, and use the template
engine's syntax to generate dynamic content.
5. Static resources: Place static resources such as CSS, JavaScript, and images in the
src/main/resources/static directory. Spring Boot will serve these resources directly without requiring
explicit controller mappings.
6. Configuration: Customize application behavior through configuration files like application.properties or
application.yml.
7. Testing: Write unit tests and integration tests for your controller methods using testing frameworks like
JUnit and Spring Test.
8. Run the application: Run your Spring Boot application using your IDE or the command line.
9. Deployment: Build an executable JAR or WAR file using your build tool. You can deploy this file to
various environments, including traditional servers or cloud platforms.
Page 14