Java U-5 Notes.pdf
Java U-5 Notes.pdf
@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;
}
@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.
@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.
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:
• - 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.
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;
}
}