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

Java U-5 Notes.pdf

Uploaded by

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

Java U-5 Notes.pdf

Uploaded by

krishnasrivas22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

What we will Discuss Today?

•How to Configure Beans in Spring Boot?


•What is Auto Wiring?
•How its Different with Old Methods?
•Benefits of Auto Wiring?
•Life Cycle of Beans
•Callback Life Cycle
Beans Configuration
In Spring, there are several styles for configuring beans, each catering to different preferences
and requirements:
1) XML Configuration: This is the traditional approach where beans and their dependencies
are configured using XML files. Beans are defined using <bean> tags, and their
dependencies are injected using attributes like ref and value. XML configuration provides a
clear separation between configuration and code, making it easy to understand and
manage.

<bean id="myService" class="com.example.MyService">


<property name="myRepository" ref="myRepository"/>
</bean>
<bean id="myRepository" class="com.example.MyRepository"/>
Beans Configuration
2) Annotation-Based Configuration: This style uses annotations such as @Component,
@Service, @Repository, and @Autowired to configure beans and their dependencies.
Beans are automatically detected and registered by Spring based on these annotations. This
approach reduces XML configuration overhead and promotes a more concise and readable
codebase.

@Service
public class MyService {
@Autowired
private MyRepository myRepository;
}
Beans Configuration
3) Java Configuration (Programmatic): With Java configuration, beans are configured using Java
classes annotated with @Configuration and @Bean. This approach allows for more type safety and
refactoring support compared to XML configuration. Beans and their dependencies are defined
programmatically within these configuration classes.
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService(myRepository());
}

@Bean
public MyRepository myRepository() {
return new MyRepository();
}
}
Beans Configuration
4) Java Configuration (Lambda-Based): This is a more concise version of Java configuration introduced
in Spring 4, leveraging lambda expressions to define beans. It provides a more functional
programming style and reduces boilerplate code.

@Configuration
public class AppConfig {
@Bean
public MyService myService(MyRepository myRepository) {
return new MyService(myRepository);
}

@Bean
public MyRepository myRepository() {
return new MyRepository();
}
}
Beans Configuration
Each bean configuration style has its advantages and is suitable for different scenarios. XML
configuration offers flexibility and clarity, annotation-based configuration reduces
boilerplate code, Java configuration provides type safety and refactoring support, lambda-
based configuration offers a more concise syntax.
What is Auto wiring?
We had discussed Old Traditional Methods of Beans Configuration in Spring Boot.
Auto-wiring helps in reducing manual code and makes your application more maintainable
and flexible by decoupling components and managing their dependencies automatically.
In Spring Boot, auto-wiring is a feature provided by the Spring framework for automatically
injecting dependencies into beans. This feature eliminates the need for explicit bean wiring
in configuration files by allowing Spring to automatically wire up the dependencies based
on their types.
How its works?
1) Dependency Injection: Spring Boot uses dependency injection to manage the
dependencies between beans. Instead of manually creating and managing instances of
objects, you define the dependencies between them, and Spring handles the instantiation
and injection of those dependencies.
Auto wiring
2) Auto-wiring: When you annotate a field, setter method, or constructor with @Autowired in a
Spring-managed component (such as a controller, service, or repository), Spring will automatically
search for a bean of the corresponding type in its application context and inject it into the
annotated field or method parameter.
@Service
public class MyService
{
private final MyRepository repository;

@Autowired
public MyService(MyRepository repository) {
this.repository = repository;
}

// Service methods that use repository...


}
In this example, the MyService class has a dependency on MyRepository, and it's being injected via
constructor auto-wiring.
Auto wiring
3) Component Scanning: Spring Boot automatically scans the packages for classes annotated with
@Component, @Service, @Repository, etc., and registers them as beans in the application context.
This allows Spring to know about the beans and their dependencies, making auto-wiring possible.
Bean Life Cycle
The lifecycle of a bean in Java Spring consists of several phases:
• Instantiation: At this stage, the Spring container creates an instance of the bean. Depending
on the bean scope, this could happen at different times, such as during application startup
for singleton beans or upon request for prototype beans.
• Population of Properties: After instantiation, the container sets the bean's properties and
dependencies, either through constructor injection, setter injection, or field injection.
• Initialization Callbacks: Before the bean is ready for use, any initialization callbacks are
invoked.
• Bean Ready for Use: At this point, the bean is fully initialized and ready for use by other
beans or components in the application.
• Usage: The bean can now be used throughout the application context, either directly or
through dependency injection.
• Destruction Callbacks: When the application context is shut down or when the bean is
explicitly destroyed, any destruction callbacks are invoked.
• Bean Destruction: After destruction callbacks are invoked, the container releases the
resources held by the bean and removes it from the application context.
Callback Life Cycle
Lifecycle callbacks in Spring allow you to perform actions during different phases of a bean's lifecycle,
such as initialization and destruction. There are several ways to define lifecycle
1) InitializingBean and DisposableBean Interfaces: Beans can implement InitializingBean and
DisposableBean interfaces, which require them to implement afterPropertiesSet() and destroy()
methods, respectively. These methods are invoked by the Spring container after the bean has
been instantiated and before it is destroyed.

public class MyBean implements InitializingBean, DisposableBean {


@Override
public void afterPropertiesSet() throws Exception {
// Initialization logic
}

@Override
public void destroy() throws Exception {
// Destruction logic
}
}
Callback Life Cycle
2) @PostConstruct and @PreDestroy Annotations: You can use the @PostConstruct and
@PreDestroy annotations to define initialization and destruction methods directly in your bean
class. These methods will be invoked by the Spring container at the appropriate lifecycle phases.

public class MyBean {


@PostConstruct
public void init() {
// Initialization logic
}

@PreDestroy
public void cleanup() {
// Destruction logic
}
}
Callback Life Cycle
3) Custom Initialization and Destruction Methods: You can define custom initialization and
destruction methods in your bean class and configure them in the Spring XML configuration
or through Java-based configuration.

public class MyBean {


public void customInitMethod() {
// Initialization logic
}

public void customDestroyMethod() {


// Destruction logic
}
}
Thank You
What we will Discuss Today?

•What is REST API?


•Why we use REST API?
•GET, POST, PUT, DELETE APIs?
•How to build Web Applications in Spring boot?
•Types of Spring Boot Build Systems.
•Structure of Spring Boot Code.
•Spring Boot Runners
•Rest Controller, Request Mapping, Request Body, Path Variable, Request Parameter
REST API
REST API
REST API
REST (Representational State Transfer) API is an architectural style for designing networked
applications. It relies on a stateless communication protocol, usually HTTP, and standard
operations (GET, POST, PUT, DELETE) to manipulate resources (data or objects) on a server.
RESTful APIs are characterized by their simplicity, scalability, and the ability to leverage
existing protocols and infrastructure.
Here are some key characteristics of RESTful APIs:
• Statelessness: Each request from a client to the server must contain all the necessary
information to understand and fulfill the request. The server should not store any client
context between requests.
• Resource-based: RESTful APIs are centered around resources, which can be any entity that
can be uniquely identified. Resources are manipulated using standard HTTP methods.
• Uniform Interface: REST APIs use a uniform interface to access resources. This typically
involves using standard HTTP methods (GET, POST, PUT, DELETE) to perform CRUD (Create,
Read, Update, Delete) operations on resources. Additionally, resources are identified by
URIs (Uniform Resource Identifiers).
REST API
Client-Server Architecture: The client and server are separate concerns, and the client is not
concerned with the data storage or business logic on the server. This allows for separation
of concerns and improved scalability.

Cacheability: Responses from the server can be labeled as cacheable or non-cacheable. This
allows clients to cache responses to improve performance.

Layered System: REST APIs can be layered, allowing for intermediaries such as proxies or
gateways to be inserted between clients and servers to improve scalability, security, or
other concerns.

RESTful APIs have become the standard for building web services due to their simplicity,
flexibility, and compatibility with existing web technologies. They are commonly used for
building APIs for web applications, mobile applications, and IoT devices, among other use
cases.
GET/ POST/ PUT/ DELETE API
GET: The GET method is used to request data from a specified resource. It's a safe and
idempotent operation, meaning it doesn't modify the resource on the server, and making
multiple identical requests should have the same effect as making a single request.
GET requests are typically used for retrieving data, such as fetching a webpage, getting user
details, or fetching a list of items from a database.
Example: GET /users retrieves a list of all users.

POST: The POST method is used to submit data to be processed to a specified resource.
It's not idempotent, meaning making multiple identical requests may have different effects each
time.
POST requests are commonly used for creating new resources, such as submitting a form,
uploading a file, or creating a new record in a database.
Example: POST /users creates a new user with the provided data in the request body.
GET/ POST/ PUT/ DELETE API
PUT: PUT method is used to update or replace an existing resource with new data at a specified
URI. It's idempotent, meaning making multiple identical requests should have the same effect as
making a single request. PUT requests are commonly used for updating existing resources, such
as modifying a user's details or updating a record in a database. When using PUT, the client
typically sends the entire updated resource in the request body, not just the fields that have
changed.
Example: PUT /users/123 updates the user with ID 123 with the provided data in the request
body.

DELETE: The DELETE method is used to request the removal of a specified resource from the
server. It's idempotent, meaning making multiple identical requests should have the same effect
as making a single request. DELETE requests are commonly used for deleting resources, such as
removing a user account, deleting a file, or deleting a record from a database.
Example: DELETE /users/123 deletes the user with ID 123 from the system.
Some Important Terms Related to the WEB API
1. Entity:
 - An Entity represents a table in a relational database. It typically maps to a database table,
with each instance of the Entity representing a row in that table.
 - In Spring Boot applications, Entities are usually annotated with `@Entity` from the JPA (Java
Persistence API) specification. This annotation tells Spring Boot that the class is a JPA entity, and
it should be mapped to a corresponding database table.
 - Entities contain fields that represent the columns in the corresponding database table, along
with getter and setter methods to access and modify these fields.
 - Example: In a simple, you might have an `Products` entity with fields like `id`, `name`, `price`,
and `qty`.
Some Important Terms Related to the WEB API
2. Repository:
 - A Repository is responsible for managing data access logic, such as querying, saving,
updating, and deleting data in a database.
 - In Spring Boot applications, Repositories are typically interfaces that extend `JpaRepository`
or a similar interface provided by Spring Data JPA. These interfaces provide methods for
common CRUD operations without requiring explicit implementation.
 - Repositories allow developers to interact with the database using object-oriented concepts
rather than writing native SQL queries.
 - Example: For the `Products` entity mentioned earlier, you might have an `ProductsRepository`
interface that allowing you to perform operations like `save`, `findById`, `findAll`, etc., on
`Products` entities.
Some Important Terms Related to the WEB API
3. Service:
 - A Service contains the business logic of an application. It co-ordinates the interactions
between multiple components, such as Entities and Repositories, to perform specific operations
or fulfill business requirements.
 - Services encapsulate the application's logic into reusable and testable components,
promoting modular and maintainable code.
 - In Spring Boot applications, Services are typically annotated with `@Service`. This annotation
tells Spring that the class is a service component and should be managed by the Spring
container.
 - Example: In an application, you might have an `ProductService` that contains methods for
creating, retrieving, updating, and deleting products. The `ProductService` would use methods
from the `ProductRepository` to interact with the database.
Creating a NEW Web Application for REST API-1
What we need:
1) My Sql Database (We will use My Sql with XAMPP)
2) VS Code
3) JDK 17 or higher
4) POSTMAN tool to check the APIs
5) Knowledge of Basic SQL Commands.

Before continue , please install these software on your computer and create a table with following
fields:
Products (id,product,details,price,qty) in a database let “DB1”
Create Table Products
(
id int primary key,
product varchar(30),
details varchar(100),
price int,
qty int
);
Creating a NEW Web Application for REST API-2
Open following website : https://start.spring.io
Add Following Dependencies:
1) Spring WEB
2) My SQL Driver
3) Leave all the settings default and Click on Generate Button
Creating a NEW Web Application for REST API-3
Download the Generated zip file and extract it into some folder, and then open this folder in VS
Code.
And do the following…………………………………………………….. Lets do it
Creating a NEW Web Application for REST API
Hope that now you have clearly understand the concept of Services, Repository, and Entities along
with the concept of REST API. Now we will discuss following topics:

• Types of Spring Boot Build Systems.


• Structure of Spring Boot Code.
• Spring Boot Runners
Spring Boot Build Systems
Spring Boot primarily supports two build systems: Maven and Gradle. Both are powerful tools for
managing dependencies, building, testing, and packaging Java applications. Here are the details:
1. Maven:
Maven is a widely-used build automation tool primarily used for Java projects. It relies on XML for
its configuration, which can be a bit verbose but is also highly configurable. Here's how Maven
works with Spring Boot:

• - pom.xml: In Maven, project configuration is stored in a file called `pom.xml` (Project Object
Model). This file includes information about the project and its dependencies.
• - Dependencies: Dependencies are managed in the `pom.xml` file. Spring Boot dependencies
can be easily included by adding them to the dependencies section with appropriate version
numbers.
• - Plugins: Maven plugins are used to execute specific goals, such as compiling code, running
tests, and packaging applications. Spring Boot Maven plugin is particularly useful for packaging
Spring Boot applications into executable JAR or WAR files.
• - Build Lifecycle: Maven has a predefined set of lifecycle phases (e.g., clean, compile, test,
package) that dictate the order in which goals are executed. These phases make it easy to
perform common tasks during the build process.
Spring Boot Build Systems

2. Gradle:
Gradle is another popular build automation tool that offers more flexibility and a Groovy-based
DSL (Domain Specific Language) for defining build scripts. Here's how Gradle works with Spring
Boot:

• - build.gradle: In Gradle, project configuration is stored in a file called `build.gradle`. This file is
typically written in Groovy (though Kotlin DSL is also supported) and defines project structure,
dependencies, and tasks.
• - Dependencies: Similar to Maven, Gradle manages dependencies, but it uses a more concise
syntax. Dependencies are declared in the `build.gradle` file, and Spring Boot dependencies can
be included using Gradle's `implementation` or `compile` configuration.
• - Plugins: Gradle has a rich ecosystem of plugins that provide additional functionality. The
Spring Boot Gradle plugin enhances Gradle's capabilities for building and packaging Spring Boot
applications.
• - Task-based: Gradle builds are organized around tasks. Each task performs a specific action,
such as compiling code, running tests, or creating a distribution. Tasks can be customized and
extended as needed.
Spring Boot Build Systems

2. Gradle:
Gradle is another popular build automation tool that offers more flexibility and a Groovy-based
DSL (Domain Specific Language) for defining build scripts. Here's how Gradle works with Spring
Boot:

• - build.gradle: In Gradle, project configuration is stored in a file called `build.gradle`. This file is
typically written in Groovy (though Kotlin DSL is also supported) and defines project structure,
dependencies, and tasks.
• - Dependencies: Similar to Maven, Gradle manages dependencies, but it uses a more concise
syntax. Dependencies are declared in the `build.gradle` file, and Spring Boot dependencies can
be included using Gradle's `implementation` or `compile` configuration.
• - Plugins: Gradle has a rich ecosystem of plugins that provide additional functionality. The
Spring Boot Gradle plugin enhances Gradle's capabilities for building and packaging Spring Boot
applications.
• - Task-based: Gradle builds are organized around tasks. Each task performs a specific action,
such as compiling code, running tests, or creating a distribution. Tasks can be customized and
extended as needed.
Structure of Spring Boot Code.
Spring Boot applications typically follow a common
structure to organize their code.

src/main/java: This directory contains the main Java


source code for your application.

src/main/resources: This directory contains non-


Java resources used by your application.

src/test/java: This directory contains the unit and


integration tests for your application.
Spring Boot Runners
Spring Boot Runners are special types of classes in a Spring Boot application that are executed
during the application startup process. These runners allow developers to perform specific tasks
or initialize certain components before the application is fully up and running.
In Spring Boot, runners are implemented using the CommandLineRunner and ApplicationRunner
interfaces. These interfaces provide a single run method that is called by the Spring Boot
framework at the appropriate time during application startup.

1) CommandLineRunner
2) ApplicationRunner
Spring Boot Runners
CommandLineRunner: This interface provides a run method with a String... args parameter. The
args parameter allows access to any command-line arguments passed to the application.
Developers can implement this interface to execute tasks that require access to command-line
arguments, such as initializing components, loading data, or performing other startup tasks.

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// Perform startup tasks here
}
}
Spring Boot Runners
2) ApplicationRunner: Similar to CommandLineRunner, this interface provides a run method but
with an ApplicationArguments parameter instead of a String... args. The ApplicationArguments
object provides access to parsed command-line arguments as well as application properties.
Developers can use this interface to perform tasks that require access to both command-line
arguments and application properties.

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class MyApplicationRunner implements ApplicationRunner {

@Override
public void run(ApplicationArguments args) throws Exception {
// Perform startup tasks here
}
}
Thanks
&
Best of Luck
// Products.java
package com.example.demo.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
//mark class as an Entity
@Entity
//defining class product as Table product
@Table
public class Products
{
@Id
@Column
int id;
@Column
String product;
@Column
String details;
@Column
int price;
@Column
int qty;
public Products() {
}
public Products(int id,String product, String details, int price, int qty)
{
this.id = id;
this.product = product;
this.details = details;
this.price = price;
this.qty = qty;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
}

---------------------------------------------------------------------------------------
// ProductsRepository.java
package com.example.demo.repository;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.model.*;
//repository that extends CrudRepository
public interface ProductsRepository extends
CrudRepository<Products,Integer>
{

}
---------------------------------------------------------------------------------------
// ProductsService.java

package com.example.demo.services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.repository.*;
import com.example.demo.model.*;
//defining the business logic
@Service
public class ProductsService
{
@Autowired
ProductsRepository productsRepository;
//getting all Products record by using the method findaAll() of
CrudRepository
public List<Products> getAllProducts()
{
List<Products> products = new ArrayList<Products>();
for(Products b:productsRepository.findAll())
{
products.add(b);
}
return products;
}
//getting a specific record by using the method findById() of
CrudRepository
public Products getProductsById(int id)
{
return productsRepository.findById(id).get();
}
//saving a specific record by using the method save() of
CrudRepository
public void saveOrUpdate(Products products)
{
productsRepository.save(products);
}
//deleting a specific record by using the method deleteById() of
CrudRepository
public void delete(int id)
{
productsRepository.deleteById(id);
}
//updating a record
public void update(Products products, int pid)
{
productsRepository.save(products);
}
}
-------------------------------------------------------------------------
// ProductsController.java

package com.example.demo;
import java.util.List;
import java.util.ArrayList;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.services.*;

import com.example.demo.model.Products;
import com.example.demo.model.*;
//mark class as Controller
@RestController
public class ProductsController
{
//autowire the ProductsService class
@Autowired
ProductsService productsService;

//creating a get mapping that retrieves all the Products detail from the
database
@GetMapping("/products")
private List<Products> getAllProducts()
{
return productsService.getAllProducts();
}
//creating a get mapping that retrieves the detail of a specific book
@GetMapping("/products/{id}")
private Products getProducts(@PathVariable("id") int id)
{
return productsService.getProductsById(id);
}
//creating a delete mapping that deletes a specified book
@DeleteMapping("/products/{id}")
private void deleteProducts(@PathVariable("id") int id)
{
productsService.delete(id);
}
//creating post mapping that post the book detail in the database
@PostMapping("/products")
private String saveProducts(@RequestBody Products products)
{
productsService.saveOrUpdate(products);
int id=products.getId();
return "OK";
}
//creating put mapping that updates the book detail
@PutMapping("/products")
private Products update(@RequestBody Products Products)
{
productsService.saveOrUpdate(Products);
return Products;
}
}

You might also like