SpringBoot Reference Notes
SpringBoot Reference Notes
Notes
[Digital Copy]
Spring Boot
Mission
• To provide quality education and learning solutions to students and working professionals in
order to enhance their practical knowledge, skills, and working experience.
• To provide an environment for high-quality education and outcome based training to students
and working professionals, equipping them with the practical knowledge, skills, and attitude
required to succeed in their personal and professional lives.
• To deliver practical, hands-on training services that prepares our students according to the
real-world challenges and opportunities, while fostering a culture of learning, execution and
continuous improvement.
Director(s)
We put our heart and effort into creating these resources with the sole objective of
helping learners reach their full potential. While every topic is prepared with great care,
we acknowledge that—being human—there may occasionally be minor errors,
incomplete details, or areas that need refinement.
If you ever come across such points, we warmly encourage you to write to us at
learn2earnlabs@[Link] or team@[Link]. Your feedback not only
helps us correct and improve, but also strengthens our mission of providing the best
quality education and guidance to every learner.
These notes are meant to serve as a direction and roadmap, not the final destination.
We encourage you to use them as a stepping stone—explore more, practice
consistently, and challenge yourself to go beyond. With dedication, the right path, and
our continuous support, you can transform yourself into a true professional and
achieve the success you deserve.
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Spring Boot
• Spring Boot is a powerful framework for building Java-based web applications and
microservices.
• It is a module of Spring through which we speed up the development processes
using Java.
• It provides a streamlined way to create stand-alone, production-grade Spring-
based applications with minimal configuration.
• It also provides a faster & easier way to setup, configure and execute the
applications.
• It simplifies the development of Java-based web applications and microservices by
providing a powerful, opinionated framework with sensible defaults and
streamlined setup.
• It's widely adopted in the industry for its productivity, scalability, and ease of use.
• Spring Boot provides a convention-over-configuration software design style, which
means developers don’t need to worry about configurations, and their efforts are
decreased because all configurations are done automatically.
• Spring boot scans the class path and then find the dependency to configure the
project automatically.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Use-Cases
Spring Boot is a versatile framework widely used across various industries and for different
types of applications.
Here are some common use cases where Spring Boot shines:
• Web Applications: Spring Boot is extensively used for building web applications,
ranging from simple websites to complex enterprise-level applications. Its
embedded server support and auto-configuration make it easy to create and
deploy web applications quickly.
• Microservices Architecture: Spring Boot's lightweight nature and ease of
development make it well-suited for building microservices-based architectures.
Each microservice can be developed as a standalone Spring Boot application,
allowing teams to independently develop, deploy, and scale services.
• RESTful APIs: Spring Boot provides excellent support for building RESTful APIs.
With Spring MVC or Spring WebFlux, developers can quickly create endpoints for
handling HTTP requests and responses. Spring Boot's auto-configuration also
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
simplifies the setup of features like JSON serialization, content negotiation, and
error handling.
• Batch Processing: Spring Batch, a module of the Spring ecosystem, integrates
seamlessly with Spring Boot for building batch processing applications. This is
particularly useful for tasks like data extraction, transformation, and loading (ETL),
scheduled jobs, and large-scale data processing.
• Real-time Data Processing: Spring Boot combined with Spring Integration or
Spring Cloud Stream is suitable for building real-time data processing applications.
It allows developers to integrate with messaging systems like Apache Kafka or
RabbitMQ, enabling the processing of streams of data in real-time.
• Event-Driven Architectures: Spring Boot can be used to build event-driven
architectures using tools like Spring Cloud Stream or Spring Cloud Event. These
enable communication and processing of events between different services or
components in a distributed system.
• Enterprise Applications: Spring Boot is widely adopted in building enterprise-
grade applications due to its robustness, scalability, and integration capabilities. It
seamlessly integrates with enterprise technologies like relational databases (using
Spring Data JPA), messaging systems, security frameworks (using Spring Security),
and more.
• IoT (Internet of Things) Applications: Spring Boot can be used to develop IoT
applications, leveraging its support for asynchronous programming, messaging
systems, and integration with IoT protocols like MQTT. This allows developers to
build scalable and reliable IoT solutions.
• Cloud-Native Applications: Spring Boot, when combined with Spring Cloud,
provides features for building cloud-native applications. This includes service
discovery, distributed configuration management, circuit breakers, and centralized
logging, which are essential for building resilient and scalable applications in cloud
environments.
• Prototyping and Rapid Development: Spring Boot's ease of setup, starter
dependencies, and auto-configuration make it an excellent choice for prototyping
and rapid development of Java-based applications. Developers can quickly get
started with building applications without spending time on boilerplate setup and
configuration.
These are just a few examples of the many use cases where Spring Boot can be applied
effectively. Its versatility, coupled with the extensive features of the Spring ecosystem,
makes it a popular choice for a wide range of applications and industries.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Spring Boot comes with several advantages, making it a popular choice for building Java-
based applications. However, it also has some disadvantages that developers should be
aware of.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Security: Spring Boot offers robust security features through Spring Security,
allowing developers to implement authentication, authorization, and other security
measures easily.
Overall, while Spring Boot offers numerous advantages for building Java-based
applications, developers should carefully evaluate their requirements and consider both
the advantages and disadvantages before choosing it for their projects.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Best Training Institute
for Graduates
Online Live Classes Also Available
Amenities
Let’s go through with the below points to understand the working flow of Spring Boot:
• Starters and Dependencies: In a Spring Boot project, you typically start by adding
dependencies to your project build configuration (such as Maven [Link] or
Gradle [Link]). These dependencies are often provided as "starters" that
encapsulate common sets of libraries and configurations for specific tasks, like web
development, database access, security, etc.
• Autoconfiguration: Once you have defined your dependencies, Spring Boot's
autoconfiguration mechanism kicks in. Spring Boot scans the classpath to detect
the presence of various libraries and automatically configures the application
based on what it finds. This includes setting up default beans, configuring
infrastructure components like data sources and servlet containers, and enabling
features based on detected dependencies.
• Embedded Server: Spring Boot includes an embedded servlet container (such as
Tomcat, Jetty, or Undertow) by default. This means you don't need to deploy your
application to a separate server; the servlet container is packaged with your
application, making it self-contained and easily deployable.
• Application Properties: Spring Boot allows you to configure your application
using properties files (typically [Link] or [Link]),
environment variables, or command-line arguments. These properties can override
the default configurations provided by Spring Boot's autoconfiguration, giving you
fine-grained control over your application's behavior.
• Component Scanning and Dependency Injection: Spring Boot leverages Spring
Framework's core features, such as component scanning and dependency
injection. Components like controllers, services, repositories, etc., are automatically
discovered and wired together using annotations like @RestController, @Service,
@Repository, etc.
• Web Layer: In a typical web application, requests are handled by controllers, which
process incoming requests, perform business logic, and generate responses.
Spring Boot simplifies the creation of RESTful APIs or web applications by providing
annotations like @RestController, @RequestMapping, @GetMapping,
@PostMapping, etc., which map HTTP requests to controller methods.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Starter POM
• In Spring Boot, a starter POM (Project Object Model) is a specialized kind of Maven
dependency that simplifies the setup of various functionalities in your Spring Boot
application.
• These starters are essentially dependency descriptors that pull in all the necessary
dependencies, configurations, and transitive dependencies needed to work with a
specific feature or technology.
• The starter POM concept in Spring Boot greatly simplifies dependency
management and configuration, allowing developers to focus more on building
their application's business logic rather than managing infrastructure and
dependencies.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
‘[Link]’ file
• The [Link] file plays a crucial role in the Spring Framework and Spring
Boot applications. It's a resource file used for automatic configuration and
component discovery.
• The [Link] file serves as a mechanism for automatic configuration,
component discovery, and extensibility in Spring Boot applications.
• It enables the dynamic registration of configurations, extensions, and
autoconfiguration classes, facilitating a more flexible and modular architecture.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
▪ Save the [Link] file.
• Update Maven Project: After adding dependencies, Maven needs to update the
project to download the required dependencies. Right-click on the project folder,
go to Maven -> Update Project. Make sure "Force Update of Snapshots/Releases"
is checked and click OK.
• Start Coding: Now you can start writing your Spring Boot application code. You
can create Java classes, controllers, repositories, etc., and use the features provided
by the added dependencies.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Here's how you can create a Spring Boot project using Spring Initializr:
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Start Coding:
▪ Once the project is imported into your IDE, you can start writing your
Spring Boot application code.
▪ Create controllers, services, repositories, etc., as needed for your
application.
▪ Configure application properties ([Link] or
[Link]) to customize your application settings.
• Run the Application:
▪ After writing your application code, you can run the Spring Boot
application by executing the main class (typically annotated with
@SpringBootApplication).
▪ This will start the embedded Tomcat server (or any other embedded
server you may have chosen) and deploy your Spring Boot
application.
That's it! You've now created a Spring Boot project using Spring Initializr and can
start developing your application. Spring Initializr simplifies the project setup
process by providing a convenient web interface for configuring project metadata
and dependencies.
Here's how you can generate a Spring Boot application using IntelliJ IDEA:
• Open IntelliJ IDEA:
▪ Launch IntelliJ IDEA and make sure you have the necessary plugins
installed for Java and Spring Boot development. The Spring Boot
support is typically included in the Java or Spring plugins.
• Create a New Project:
▪ Go to File -> New -> Project.
▪ Choose Spring Initializr from the list of options on the left.
• Configure Project:
▪ In the Spring Initializr dialog, you can configure your Spring Boot
project:
▪ Choose the appropriate JDK.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Best Training Institute
for Graduates
Online Live Classes Also Available
Amenities
Project Testing
a) Check whether all things are configured and working fine. You need to go through
following steps
1. Initially, remove all the unused dependencies from [Link] file because you
don’t have too much things available at the beginning.
2. & Run the java application using main class file (@SpringBootApplication).
If you want to change the running port of your web server then add the below syntax
inside your “src/main/resources/[Link]” file
[Link]=3000
Now you can access your controller functionality at “localhost:3000/home”
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
1. First create your Spring Starter Project & make sure the internet is available in your
system.
2. Then enter group id, artifact id, version, description and package name. Click next
3. Then select the dependency for Spring Web. Click Next and then Finish.
4. You will get a main class file (defined using @SpringBootApplication Annotation)
inside your project package and now create a controller class
[Link]
package [Link];
import [Link];
import [Link];
@Controller
public class AppController {
@RequestMapping("/home")
public String welcomePage() {
return "home"; //the jsp page you need to render
}
}
5. Now, you need to configure the ViewResolver. If you want to configure JSP view
resolver using [Link] file in Spring Boot, you can do so by setting
the properties related to the JSP resolver. Here's how you can configure it:
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Note : The above configuration is not necessary for basic setup in most cases.
6. Now create a folder (named: webapp) inside src/main and inside webapp folder
create folder ‘WEB-INF’ and inside WEB-INF create folder ‘views’, where you need
to create/store the jsp pages.
WEB-INF/views/[Link]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html><head><meta charset="ISO-8859-1">
<title>Insert title here</title></head>
<body>
<h1>Welcome Participants!!!</h1><hr>
The Spring boot training is conducted by Learn2Earn Labs - Best Training
Institute for Corporate Professionals and Graduate Students.
</body></html>
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
7. “tomcat-embed-jasper” dependency
In a Spring Boot project, adding the tomcat-embed-jasper dependency may be
required if you're using JSP (JavaServer Pages) for your web views.
Remember, if you're not using JSP, you don't need to include this dependency.
You can stick with Thymeleaf, FreeMarker, or any other template engine
supported by Spring Boot.
8. Now run the Project or Java Application using the main class file.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Example : Handling multiple JSP file in MVC Project using Spring Boot
[Link]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head><meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Welcome Participants!!!</h1>
<hr>
The Spring boot training is conducted by Learn2Earn Labs - Best Training Institute
for Corporate Professionals and Graduate Students.
</body>
</html>
[Link]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head><meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>About - Learn2Earn Labs</h1>
<hr>
Learn2Earn Labs is one of those limited Institute, offers Job Guarantee, Industry-
Oriented & Skill Development Training Programs with guaranteed starting package
range of 4-6 LPA on Six Months Training, 6-8 LPA on One Year Training and more
than 10 LPA Package on Two Years Training Programs.
</body>
</html>
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Contact Us</h1>
<hr>
For more Details, visit our website : [Link] [Link]
or drop a WhatsApp @+91-9548868337
</body>
</html>
[Link]
package [Link];
import [Link];
import [Link];
@Controller
public class AppController {
@RequestMapping("/")
public String welcomePage() {
return "home";
}
@RequestMapping("/about")
public String aboutPage() {
return "about";
}
@RequestMapping("/contact")
public String contactPage(){
return "contact";
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
package [Link];
import [Link];
import [Link];
@SpringBootApplication
public class SpringBootDemoApplication {
[Link]
[Link]=SpringBootDemo
# JSP View Resolver Configuration
[Link]=/WEB-INF/views/
[Link]=.jsp
• [Link]
• [Link]
• [Link]
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link] File
• The [Link] file in Spring Boot is a key component for configuring
your application.
• The [Link] file serves as a central place for configuring your Spring
Boot application, making it easy to manage various settings and parameters
without the need for extensive code changes.
• It's a standard Java Properties file that allows you to define various properties and
settings for your Spring Boot application. These properties control different aspects
of your application, such as database connection settings, logging configuration,
server port, and much more.
1. Configuration Properties
You can define properties in the [Link] file using a key-value pair
format, where each property is written as key=value.
2. Application Settings
a) Server Configuration: You can configure the embedded web server's settings
like port number, context path, SSL configuration, etc.
[Link]=8080
[Link]-path=/myapp
[Link]=false
b) Logging Configuration: You can control the logging levels and appenders.
[Link]=INFO
[Link]=[Link]
c) Datasource Configuration: If your application connects to a database, you can
specify the database connection properties.
[Link]=jdbc:mysql://localhost:3306/mydatabase
[Link]=root
[Link]=secret
3. Custom Properties
You can define your own custom properties in the [Link] file and
access them in your Spring beans using @Value annotation or by injecting them
directly using @ConfigurationProperties.
[Link]=value
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
4. Profiles
You can define profile-specific configurations by creating separate application-
{profile}.properties files.
The properties defined in these profile-specific files override the properties defined
in the default [Link] file when the corresponding profile is active.
# [Link]
[Link]=jdbc:mysql://localhost:3306/appdatabase
5. Externalizing Properties
You can externalize the [Link] file outside of your packaged JAR or
WAR file by placing it in a predefined location.
This allows you to configure your application differently for different environments
without changing the packaged artifact.
7. Property Hierarchy
Spring Boot supports a hierarchy of property sources, allowing you to define
properties in different locations like system properties, environment variables,
YAML files, and property files, with different precedence levels.
If you want to learn about the various properties that can be specified inside
your [Link] file, then you can go through the below url:
[Link]
[Link]#[Link]-properties
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
[Link]=SpringBootDemo
# JSP View Resolver Configuration
[Link]=/WEB-INF/views/
[Link]=.jsp
# Set the server port to 8080
[Link]=3000
# Define the context path of the application
[Link]-path=/myapp
# Define a custom property
[Link]=value
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@SpringBootApplication
public class SpringBootDemoApplication {
public static void main(String[] args) {
[Link]([Link], args);
}}
@Component
class MyComponent {
@Value("${[Link]}")
private String customProperty;
@PostConstruct
public void doSomething() {
[Link]("Custom property value: " + customProperty);
}}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Best Training Institute
for Graduates
Online Live Classes Also Available
Amenities
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Criteria API: JPA provides a Criteria API for building dynamic queries using a type-
safe and object-oriented approach. Criteria queries are defined programmatically
using a set of builder classes and methods provided by the Criteria API. This
approach can be more flexible and less error-prone than JPQL for complex queries.
Yes, JPA (Java Persistence API) is an ORM (Object-Relational Mapping) tool. It provides a
standardized way for Java developers to map Java objects to relational database tables
and perform database operations using an object-oriented approach.
JPA defines a set of interfaces and annotations that ORM frameworks can implement to
provide ORM capabilities in Java applications. These capabilities include mapping Java
classes to database tables, defining relationships between entities, executing queries, and
managing entity lifecycle.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
While JPA itself is a specification and does not provide its own implementation, there are
several ORM frameworks that implement the JPA specification, such as Hibernate,
EclipseLink, and OpenJPA. Developers can choose the ORM framework that best suits their
needs and preferences while still using the standard JPA API for database interactions.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Flexibility: Hibernate offers more flexibility and control over database interactions
compared to JPA. Developers can leverage Hibernate-specific features and
configurations for advanced use cases.
• Compliance: Using JPA ensures compliance with Java EE standards and best
practices. Applications built with JPA are more likely to adhere to industry
standards and benefit from community support and contributions.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Both JPA and Hibernate are powerful tools for working with relational databases in
Java applications.
• JPA and Hibernate are both valuable tools for working with relational databases in
Java applications, each with its own strengths and use cases.
• JPA provides standardization and portability, while Hibernate offers advanced
features and customization options for complex ORM scenarios.
• The choice between JPA and Hibernate depends on the specific requirements and
constraints of the project.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Complex Mapping and Querying: Hibernate is well-suited for scenarios that require
complex object-relational mapping or querying capabilities. It provides advanced
features for mapping inheritance hierarchies, associations, and custom data types
to database tables.
• Performance Optimization: Hibernate offers various performance optimization
techniques, such as caching, lazy loading, and batch processing, to improve the
performance of database operations. These features are especially useful in
applications with high data volume or complex data access patterns.
• Legacy Systems Integration: Hibernate can be used to integrate Java applications
with existing legacy systems or databases. It provides support for mapping legacy
database schemas to Java objects and performing database operations using
modern ORM techniques.
• Batch Processing and ETL (Extract, Transform, Load): Hibernate's batch processing
capabilities make it suitable for ETL (Extract, Transform, Load) tasks and batch
processing jobs. Developers can efficiently process large volumes of data and
perform bulk database operations using Hibernate's batch processing features.
• Customization and Extensibility: Hibernate offers extensive customization and
extensibility options, allowing developers to fine-tune the behavior of the ORM
framework according to their specific requirements. Developers can customize
entity mappings, query execution plans, and transaction management strategies
using Hibernate's configuration options and extension points.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Entity Classes: Define your domain model using entity classes. An entity class
represents a table in the database. Each entity is typically annotated with @Entity,
and properties are mapped to columns using annotations like @Column, @Id,
@GeneratedValue, etc.
import [Link];
import [Link];
import [Link];
import [Link];
@Entity
public class Product {
@Id
@GeneratedValue(strategy = [Link])
private Long id;
private String name;
private double price;
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
import [Link];
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
@Transactional
public Product saveProduct(Product product) {
return [Link](product);
}
// Other service methods...
}
• Using JPA in Controllers or Services: Finally, you can inject repository interfaces
or entity manager directly into your controllers or services to perform database
operations.
@RestController
public class ProductController {
@Autowired
private ProductService productService;
@PostMapping("/products")
public ResponseEntity<Product> createProduct(@RequestBody Product
product) {
Product savedProduct = [Link](product);
return [Link](savedProduct);
}
By following above steps, you can easily integrate JPA with Spring Boot to build data-
driven applications efficiently, leveraging Spring Boot's auto-configuration and
dependency management capabilities. JPA provides a high-level abstraction for working
with databases, while Spring Boot simplifies the setup and configuration, making
development faster and more manageable.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
1. First create your Spring Starter Project & make sure the internet is available in your
system.
2. Then enter group id, artifact id, version, description and package name. Click next
3. Then select the dependency for Spring Data JPA and MySQL Driver. Click Next and
then Finish.
4. Now create an Entity class
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Entity
public class Employee {
@Id
@GeneratedValue(strategy=[Link])
int empId;
String empName;
String empCity;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
[Link] = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
[Link] = empName;
}
public String getEmpCity() {
return empCity;
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
5. Then creating the Repository interface for providing generic CRUD operations for
a specific type
[Link]
package [Link];
import [Link];
public interface EmployeeRepository extends CrudRepository<Employee,
Integer>{
}
Where Employee is the entity name and Integer is the type of ID or primary key.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
@SpringBootApplication
public class SpringbootjpaApplication {
Employee emp=[Link](employee);
[Link](emp);
}
Note: make sure that MySQL server should be available in your computer and must have
database available, named “springbootdb”.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@SpringBootApplication
public class SpringbootjpaApplication {
public static void main(String[] args) {
ConfigurableApplicationContext
context=[Link]([Link], args);
EmployeeRepository
employeeRepository=[Link]([Link]);
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
@SpringBootApplication
public class SpringbootjpaApplication {
Iterable<Employee> employees=[Link]();
[Link]("available records in the database : ");
for(Employee employee:employees)
[Link](employee);
}
}
Where, Optional is a container object that may or may not contain a non-null value. It is
a part of the Java 8 API introduced to handle situations where a method may or may not
return a value.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@SpringBootApplication
public class SpringbootjpaApplication {
Optional<Employee> employeeOptional =
[Link](4);
Employee employee = [Link]();
[Link]("Karan Singh");
[Link](employee);
[Link]("updated employee details are : "+employee);
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Best Training Institute
for Graduates
Online Live Classes Also Available
Amenities
Finder Methods
• In Spring Boot, finder methods refer to methods defined in Spring Data
repositories that automatically generate queries based on the method name.
• These methods are used to query entities from the underlying data source (such
as a database) without having to write custom queries explicitly.
• Spring Data repositories support various query creation strategies, including
method name conventions, @Query annotation, and Querydsl.
Here, the findByAgeGreaterThan method uses a JPQL query to find users with an
age greater than a specified value.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Querydsl
Querydsl is a framework that allows you to write type-safe queries in Java. Spring
Data JPA integrates with Querydsl, enabling you to use Querydsl predicates in
repository methods.
For example:
public interface UserRepository extends JpaRepository<User, Long>,
QuerydslPredicateExecutor<User> {
List<User> findAll(Predicate predicate);
}
With this setup, you can create complex queries using Querydsl predicates and
pass them to the findAll method.
By leveraging these finder methods, you can easily define and execute queries without
writing boilerplate SQL code, making your codebase more readable and maintainable.
[Link]
package [Link];
import [Link];
import [Link];
public interface EmployeeRepository extends CrudRepository<Employee, Integer>{
public ArrayList<Employee> findByEmpName(String empName);
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@SpringBootApplication
public class SpringbootjpaApplication {
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
}
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@SpringBootApplication
public class SpringbootjpaApplication {
int empId=1;
ArrayList<Employee>
employees=[Link](empId);
[Link]("Available records with Id greater than = "+empId);
for(Employee employee:employees)
[Link](employee);
If you want to explore more then kindly go through with the below link:
[Link]
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
1. First create your Spring Starter Project & make sure that internet is available in your
system.
2. Then enter group id, artifact id, version, description and package name. Click next
3. Then select the dependency for Spring Data JPA and Spring Data MongoDB. Click
Next and then Finish.
4. Now create an document class
[Link]
package [Link];
import [Link];
@Document(collection="employee")
public class Employee {
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
public Employee() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName + ", empCity="
+ empCity + "]";
}
}
[Link]
package [Link];
import [Link];
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@SpringBootApplication(exclude = {[Link]})
public class SpringbootmongoApplication {
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Employee emp=[Link](employee);
[Link](emp);
}
}
Note : Spring Boot expects a DataSource configuration by default, but if you're using
MongoDB which doesn't require a DataSource then you need to tell Spring Boot not to
expect a DataSource configuration. You can do this by excluding
DataSourceAutoConfiguration like:
@SpringBootApplication(exclude = {[Link]})
By excluding [Link], you're telling Spring Boot not to expect
a DataSource configuration.
[Link]=springbootmongo
[Link]=localhost
[Link]=27017
[Link]=empdata
8. Now run your application but make sure than the database (named ‘empdata’)
must be available in your mongodb database.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
1. First create your Spring Starter Project & make sure that internet is available in your
system.
2. Then enter group id, artifact id, version, description and package name. Click next
3. Then select the dependency for Spring Web and Spring Data MongoDB. Click Next
and then Finish.
4. Now create an Entity class ([Link] – As same as previous)
5. Create Repository interface ([Link] – As same as previous).
6. Create Controller
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@RestController
@RequestMapping("/employee")
public class AppController {
@Autowired
private EmployeeRepository employeeRepository;
@PostMapping("/")
public ResponseEntity<?> addEmployee(@RequestBody Employee employee)
{
Employee emp=[Link](employee);
return [Link](emp);
}
@GetMapping("/")
public ResponseEntity<?> viewEmployees()
{
return [Link]([Link]());
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]=springbootmongo
[Link]=localhost
[Link]=27017
[Link]=empdata
8. Now run your application and use postman for adding & getting the employee
details.
For adding the details you need to pass the following JSON data in the request body:
{
"empId":"12",
"empName":"Shweta Sharma",
"empCity":"Jaipur"
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Using Postman
Step 1: Install Postman
you can download it from the official website:
[Link]
For example:
{
"name": "emp_name",
"city": "emp_city"
}
Click the "Send" button to send the request.
Postman will display the response from your server, showing the newly added
employee.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Selecting the Request Method: Ensure that you've selected the correct request
method (e.g., POST) from the dropdown menu next to the request URL.
• Entering the Request URL: Enter the URL for the API endpoint you want to send
the request to. For example, if you're testing a POST request to add a new
employee, the URL might be something like [Link]
• Choosing the Body Type: In Postman, switch to the "Body" tab located below
the request URL input field.
• Selecting the Body Format: In the "Body" tab, select the format of the data
you're sending. Since you're sending JSON data, choose the "raw" option.
• Choosing JSON Format: Once you've selected "raw," a dropdown menu will
appear next to it. Click on the dropdown menu and choose "JSON."
• Writing JSON Data: Now, you can write your JSON data in the text area
provided below.
For example, if you're adding a new employee, your JSON data might look like this:
{
"name": "emp_name",
"city": "emp_city"
}
• Sending the Request: After entering the JSON data, click the "Send" button to
send the request.
By following the above process steps, you will be able to write JSON data in Postman
and send requests to your backend API for testing.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
1. First create your Spring Starter Project & make sure that internet is available in your
system.
2. Then enter group id, artifact id, version, description and package name. Click next
3. Then select the dependency for Spring Web and Spring Data MongoDB. Click Next
and then Finish.
4. Now, include the tomcat-embed-jasper dependency to can handle JSP pages in
your Spring Boot project ([Link]) using Maven:
<dependency>
<groupId>[Link]</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
@Controller
@RequestMapping("/employee")
public class AppController {
@Autowired
private EmployeeRepository employeeRepository;
@PostMapping("/add")
public String addEmployee(@RequestParam int id, @RequestParam String name,
@RequestParam String city, Model model) {
Employee employee = new Employee();
[Link](id);
[Link](name);
[Link](city);
[Link](employee);
[Link]("message", "Employee added successfully!");
return "addEmployee"; // Return [Link]
}
@GetMapping("/add")
public String showAddEmployeeForm() {
return "addEmployee"; // Return [Link]
}
@GetMapping("/view")
public String viewEmployees(Model model) {
List<Employee> employees = [Link]();
[Link]("employees", employees);
return "viewEmployees"; // Return [Link]
}
}
8. Now, modifying the project facets then select the Dynamic Web Module and click
on “Apply & Close” for getting the project structure according to web
requirements.
9. Create a folder with name ‘views’ inside src/main/webapp/WEB-INF to create/store
the jsp pages.
10. Use the given codes for creating jsp pages, SpringBootApplication class and
configuring project through [Link] file.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Add Employee</title>
</head>
<body>
<h2>Add Employee</h2>
<form action="/employee/add" method="post">
<label for="id">Employee ID:</label><br>
<input type="text" id="id" name="id"><br>
<label for="name">Employee Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="city">Employee City:</label><br>
<input type="text" id="city" name="city"><br><br>
<input type="submit" value="Submit">
</form>
<p>${message}</p> <!-- Display success or error message -->
</body>
</html>
[Link]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page isELIgnored="false" %>
<%@ page import="[Link],[Link]" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>View Employees</title>
</head>
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
<body>
<h2>Employees List</h2>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>City</th>
</tr>
</thead>
<tbody>
<%
List<Employee> employees = (List<Employee>)
[Link]("employees");
if (employees != null) {
for (Employee employee : employees) {
%>
<tr>
<td><%= [Link]() %></td>
<td><%= [Link]() %></td>
<td><%= [Link]() %></td>
</tr>
<%
} }
%>
</tbody>
</table>
</body>
</html>
[Link]
[Link]=springbootmongo
[Link]=localhost
[Link]=27017
[Link]=empdata
[Link]=/WEB-INF/views/
[Link]=.jsp
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
@SpringBootApplication(exclude = {[Link]})
public class SpringbootmongoApplication {
Now, run your springbootapplication class and execute the project functionality.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Best Training Institute
for Graduates
Online Live Classes Also Available
Amenities
Concept of API
APIs allow developers to access the functionality of a system or service without having to
understand its internal workings. They provide a level of abstraction that simplifies the
development process and promotes code reusability. APIs can be used to perform a wide
range of tasks, such as retrieving data from a database, sending emails, or interacting with
external services.
Types of APIs
Example: The OpenWeatherMap API allows developers to retrieve weather data for
a specific location by sending an HTTP request to their API endpoint.
• Library APIs
• These APIs are provided by software libraries and allow developers to access
the functionality of the library in their own code.
• Library APIs are used to perform specific tasks, such as manipulating images,
parsing JSON data, or encrypting data.
Example: The axios library in [Link] provides an API for making HTTP requests.
Developers can use the [Link]() method to send a GET request to a server and
retrieve data.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Example: The Windows API provides a set of functions that allow developers to
create and manage windows, handle user input, and perform other tasks related
to the Windows operating system.
There are several types of APIs, each with its own set of characteristics and use cases. The
choice of API type depends on the specific requirements of your application, including
the desired level of complexity, scalability, and performance.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• GraphQL API
• GraphQL is a query language for APIs that allows clients to request only the
data they need.
• Unlike RESTful APIs, which expose a fixed set of endpoints, GraphQL APIs
have a single endpoint and allow clients to specify the structure of the
response.
• This makes GraphQL APIs more flexible and efficient for fetching data in
complex applications.
• WebSocket API
• WebSocket is a communication protocol that provides full-duplex
communication channels over a single TCP connection.
• WebSocket APIs allow for real-time, bidirectional communication between
clients and servers, making them ideal for applications that require low-
latency updates, such as chat applications and online gaming platforms.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Social Media APIs: Social media platforms like Facebook, Twitter, and Instagram
provide APIs that allow developers to access their platform's features, such as
posting updates, retrieving user information, and interacting with friends.
• Payment Gateway APIs: Payment gateway services like PayPal, Stripe, and
Braintree provide APIs that allow developers to integrate payment processing into
their applications. Developers can use these APIs to accept payments, issue
refunds, and manage transactions.
• Maps APIs: Mapping services like Google Maps and Mapbox provide APIs that
allow developers to integrate mapping functionality into their applications.
Developers can use these APIs to display maps, get directions, and perform
geocoding tasks.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
REST API
• REST (Representational State Transfer) is an architectural style for designing
networked applications.
• It is commonly used in web services development, particularly in the context of
APIs (Application Programming Interfaces) for web-based applications.
• The fundamental idea behind REST is to treat resources as unique entities that can
be manipulated using a standard set of operations.
• REST APIs provide a standardized way for systems to communicate over the web,
enabling interoperability between different applications and services.
• Resources: In REST, everything is a resource. A resource can be any entity that can
be uniquely identified, such as a user, a blog post, or an image. Resources are
typically identified by URIs (Uniform Resource Identifiers).
• HTTP Methods: RESTful APIs use HTTP methods to perform actions on resources.
The most commonly used HTTP methods in RESTful APIs are:
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Uniform Interface: REST APIs should have a uniform interface, meaning that the
same set of HTTP methods should be applicable to all resources. This simplifies the
API and makes it more predictable.
• Statelessness: Each request from a client to the server must contain all the
information necessary to understand the request. The server should not store any
client state between requests. This makes the system more scalable and reliable.
• Versioning: As APIs evolve over time, it's often necessary to introduce changes
that may not be backward compatible. Versioning allows clients to specify which
version of the API they wish to interact with, enabling them to adapt to changes at
their own pace. Versioning can be done in various ways, such as including the
version number in the URI (e.g., /v1/resource) or using custom request headers.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Error Handling: APIs should provide informative error responses to help clients
diagnose and resolve issues. This includes using appropriate HTTP status codes
(e.g., 4xx for client errors, 5xx for server errors) and including detailed error
messages in the response body.
• Pagination: When dealing with large collections of resources, it's common for APIs
to support pagination to limit the amount of data returned in each response.
Pagination parameters (e.g., page and per_page) allow clients to request specific
subsets of the data, improving performance and reducing bandwidth usage.
• Content Negotiation: REST APIs can support content negotiation to allow clients
to specify the desired representation format (e.g., JSON, XML) for responses. This
is typically done using the Accept header in the request, and servers can use the
Content-Type header in responses to indicate the format of the returned data.
• Rate Limiting: To prevent abuse and ensure fair usage of resources, APIs often
implement rate-limiting mechanisms to restrict the number of requests that clients
can make within a certain time period. Rate limits can be enforced globally or on a
per-user basis, and clients are typically notified of rate limit exceeded errors when
they exceed their allowed quota.
These additional aspects play crucial roles in designing robust, secure, and efficient REST
APIs that meet the needs of both clients and servers.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• To use DevTools in a Spring Boot project, you typically need to include the spring-
boot-devtools dependency in your project's [Link] (if using Maven) or
[Link] (if using Gradle).
• To add DevTools to a Maven-based Spring Boot project, you need to open your
project's [Link] file and Add the spring-boot-devtools dependency within the
<dependencies> section:
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
Save the [Link] file.
• Once you've added the dependency, DevTools will be automatically enabled when
you run your Spring Boot application in development mode (spring-boot:run). You
can then take advantage of features such as automatic restart, live reload, and
property defaults to streamline your development workflow.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Note : You can also customize DevTools behavior by configuring properties in your
[Link] or [Link] file.
For example, you can disable specific features or customize the classpath scanning
behavior. Refer to the official Spring Boot documentation for more information on
configuring and using Spring Boot DevTools Documentation
[Link]
boot/docs/current/reference/html/[Link]#[Link]
Lombok
• Lombok is a library for Java that helps reduce boilerplate code in projects.
• In the context of Spring Boot, Lombok is often used to simplify the creation of Java
classes, particularly data classes such as entities, DTOs (Data Transfer Objects), and
POJOs (Plain Old Java Objects).
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Integration with IDEs: Lombok seamlessly integrates with popular IDEs such as
IntelliJ IDEA, Eclipse, and NetBeans. IDE plugins automatically recognize Lombok
annotations and provide code assistance, navigation, and refactoring support as if
the code were written manually.
• Immutable Objects: Lombok provides annotations such as @Value and @Builder
to create immutable objects and builder patterns, respectively. Immutable objects
are thread-safe and can simplify concurrent programming.
• Logging: Lombok offers annotations like @Slf4j and @Log to automatically
generate logger fields in classes, reducing the need to declare logger instances
explicitly.
• Cleaner Code: By reducing boilerplate code, Lombok helps improve code
readability and maintainability. Developers can focus on writing business logic
rather than repetitive code structures.
To use Lombok in a Java project, including a Spring Boot application, you'll need to follow
a few simple steps:
• Step 1: Add Lombok Dependency to Your Project
If you're using Maven, add the Lombok dependency to your [Link]:
<dependency>
<groupId>[Link]</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version> <!-- Use the latest version -->
<scope>provided</scope>
</dependency>
If you're using Gradle, add the Lombok dependency to your [Link]:
dependencies {
compileOnly '[Link]:lombok:1.18.20' // Use the latest version
annotationProcessor '[Link]:lombok:1.18.20' // Use the latest
version
}
• Step 2: Install Lombok Plugin in Your IDE
To enable Lombok support in your IDE (e.g., IntelliJ IDEA, Eclipse, or NetBeans),
you'll need to install the Lombok plugin. Instructions for installing the plugin can
be found on the Lombok website.
Go to help>install new software> then install the Lombok plugin using the url:
[Link]
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
import [Link];
@Data
public class User {
private Long id;
private String username;
private String email;
}
• @Getter / @Setter: Generates getter or setter methods for fields.
import [Link];
import [Link];
@Getter @Setter
public class User {
private Long id;
private String username;
private String email;
}
import [Link];
import [Link];
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String username;
private String email; }
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• @Builder: Generates a builder pattern for the class, allowing for fluent object
creation.
import [Link];
import [Link];
@Data
@Builder
public class User {
private Long id;
private String username;
private String email;
}
Class Assignment : Create REST API’s for Update & Delete Operation.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
1. First create a spring starter project with three dependencies – Spring Web, Spring
Data JPA and MySQL Driver.
2. Add the Lombok Dependency and Spring DevTools Dependency to your project
[Link] file
<dependency>
<groupId>[Link]</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version> <!-- Use the latest version -->
<scope>provided</scope>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
3. Define the Model or Entity
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
@Entity
@Data
public class Employee {
@Id
private int empId;
private String empName;
private String empDept;
private String empCity;
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
package [Link];
import [Link];
[Link]
package [Link];
import [Link];
import [Link];
@Service
public class EmployeeService {
EmployeeRepository employeeRepository;
public EmployeeService(EmployeeRepository employeeRepository)
{
[Link]=employeeRepository;
}
public List<Employee> getAllEmployee()
{
return [Link]();
}
public Employee getEmployee(int empId)
{
return [Link](empId).get();
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@RestController
@RequestMapping("/api")
public class AppController {
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
EmployeeService employeeService;
@GetMapping("/employee")
public List<Employee> getAllEmployeeDetails()
{
return [Link]();
}
@GetMapping("/employee/{empId}")
public Employee getEmployeeDetails(@PathVariable("empId") int
empId)
{
return [Link](empId);
}
@PostMapping("/employee")
public String addEmployeeDetails(@RequestBody Employee
employee)
{
String message=[Link](employee);
return message;
@PutMapping("/employee")
public String updateEmployeeDetails(@RequestBody Employee
employee)
{
String
message=[Link](employee);
return message;
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
@DeleteMapping("/employee/{empId}")
public String deleteEmployeeDetails(@PathVariable("empId") int
empId)
{
String message=[Link](empId);
return message;
}
}
8. SpringBootApplication Class
package [Link];
import [Link];
import [Link];
@SpringBootApplication
public class SpringbootapiApplication {
public static void main(String[] args) {
[Link]([Link], args);
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
To Check the API Functionality, you need to use postman and make sure that the database
with name “springbootdb” should be available at your MySQL Server.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Best Training Institute
for Graduates
Online Live Classes Also Available
Amenities
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Define Custom Error Response Payload: Create a custom class to represent the
error response payload. This class will contain details such as error code, message,
timestamp, etc.
public class ErrorResponse {
private HttpStatus status;
private String message;
private LocalDateTime timestamp;
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler([Link])
public ResponseEntity<Object>
handleResourceNotFoundException(ResourceNotFoundException ex) {
// Create custom error response
ErrorResponse errorResponse = new
ErrorResponse(HttpStatus.NOT_FOUND, [Link](),
[Link]());
return new ResponseEntity<>(errorResponse,
HttpStatus.NOT_FOUND);
}
@ExceptionHandler([Link])
public ResponseEntity<Object> handleGlobalException(Exception ex) {
// Create custom error response for other exceptions
ErrorResponse errorResponse = new
ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, [Link](),
[Link]());
return new ResponseEntity<>(errorResponse,
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
• Use Exception Handling in Controllers: In your controller methods, throw
custom exceptions when necessary.
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/resource/{id}")
public ResponseEntity<Object> getResource(@PathVariable Long id) {
// Logic to fetch resource by id
Resource resource = [Link](id);
if (resource == null) {
throw new ResourceNotFoundException("Resource with id " + id +
" not found");
}
return new ResponseEntity<>(resource, [Link]);
}}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Logging: Ensure that exceptions are properly logged for debugging and
monitoring purposes.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler([Link])
public ResponseEntity<Object>
handleResourceNotFoundException(ResourceNotFoundException ex) {
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
package [Link];
import [Link];
@Data
public class Employee {
private int empId;
private String empName;
private String empCity;
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable int
id) {
Employee employee = [Link](id);
if (employee == null) {
throw new EmployeeNotFoundException("Employee with ID " + id
+ " not found");
}
return new ResponseEntity<>(employee, [Link]);
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Service – [Link]
package [Link];
import [Link];
import [Link];
import [Link];
@Service
public class EmployeeService {
static {
[Link](new Employee(1, "Sumita Garg", "Jaipur"));
[Link](new Employee(2, "Tushar Gupta", "Ghaziabad"));
}
if ([Link]() == id) {
return employee;
}
}
return null; // Employee not found
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler([Link])
public ResponseEntity<Object>
handleEmployeeNotFoundException(EmployeeNotFoundException ex) {
@ExceptionHandler([Link])
public ResponseEntity<Object> handleGlobalException(Exception ex) {
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
import [Link];
import [Link];
import [Link];
@Data
public class ErrorResponse {
private HttpStatus status;
private String message;
private LocalDateTime timestamp;
8. Application Properties
Configure the application properties such as server port, database configuration
(if required), etc., in the [Link] file.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Best Training Institute
for Graduates
Online Live Classes Also Available
Amenities
• Controller Methods
• In Spring MVC, controllers are responsible for handling HTTP requests and
generating HTTP responses.
• Controller methods typically return objects that represent the data to be
sent back in the response.
• Spring Boot automatically serializes these objects into the appropriate
format (e.g., JSON, XML) based on the Accept header in the request.
• You can annotate controller methods with @ResponseBody to indicate that
the return value should be serialized and included in the response body.
• Error Handling
• Spring Boot offers several mechanisms for handling errors and exceptions
that occur during request processing.
• You can define global exception handlers using @ControllerAdvice
annotated classes or specific exception handlers within individual
controllers.
• Error handlers can return custom error responses, log errors, or perform
other actions based on the type of error.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Interceptors
• Interceptors in Spring MVC allow you to intercept and modify both requests
and responses before they reach the controller or after they leave the
controller.
• You can create custom interceptors by implementing the
HandlerInterceptor interface and registering them using the
WebMvcConfigurer interface.
• Interceptors provide a centralized location for common response handling
tasks such as adding headers, logging, or modifying the response body.
• Filters
• Filters are another mechanism for intercepting and modifying HTTP
requests and responses.
• Unlike interceptors, filters operate at a lower level in the servlet container
and can intercept requests and responses before they reach the Spring MVC
dispatcher servlet.
• Filters are ideal for tasks such as content transformation, request/response
logging, or security enforcement.
• Content Negotiation
• Spring Boot supports content negotiation, allowing clients to specify the
desired representation format (e.g., JSON, XML) using the Accept header.
• You can configure content negotiation settings in Spring Boot to choose
the appropriate response format based on the client's preferences.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• HTTP Headers
• HTTP headers provide additional metadata about the response, such as
content type, caching directives, and security policies.
• Controllers, interceptors, and filters can set HTTP headers in the response
using methods provided by the HttpServletResponse object or using
convenience methods provided by Spring Boot.
[Link]
package [Link];
import [Link];
@Data
public class Employee {
private int empId;
private String empName;
private String empCity;
public Employee(int empId, String empName, String empCity) {
super();
[Link] = empId;
[Link] = empName;
[Link] = empCity;
}
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
@Service
public class EmployeeService {
// Mock data for demonstration
private static final List<Employee> employees = new ArrayList<>();
static {
[Link](new Employee(1, "Sumita Garg", "Jaipur"));
[Link](new Employee(2, "Tushar Gupta", "Ghaziabad")); }
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@RestController
@RequestMapping("/employee")
public class AppController {
@Autowired
private EmployeeService employeeService;
@GetMapping("/{id}")
public ResponseEntity<Object> getEmployeeById(@PathVariable int id) {
return [Link]("Employee details has
been fetched",
[Link], [Link](id)
);
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
1. First create project with dependency spring web, Lombok & spring dev tools.
2. Then define the controller
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@RestController
public class AppController {
@PostMapping("/upload")
public ResponseEntity<String> fileUpload(@RequestParam("file")
MultipartFile file ){
if([Link]()) {
return
[Link](HttpStatus.INTERNAL_SERVER_ERROR).body("No file
is available to upload");
}
boolean status=uploadFile(file);
if(status==true)
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
return
[Link](HttpStatus.INTERNAL_SERVER_ERROR).body("file
uploading failed");
else
return
[Link](HttpStatus.INTERNAL_SERVER_ERROR).body("file
uploading failed");
}
try {
[Link]([Link](),
[Link](dirPathToUpload+[Link]+[Link]()),Stan
dardCopyOption.REPLACE_EXISTING);
status=true;
} catch (IOException e) {
// TODO Auto-generated catch block
[Link]();
}
return status;
}
}
3. Using postman to upload / pass the file, send request & check the response
To pass a file using Postman as a request, you can use the "form-data" or "binary"
mode in the body of the request. Here's how to do it:
a) Open Postman: Launch the Postman application.
b) Create a New Request: Either create a new request or open an existing one
where you want to pass a file.
c) Select Appropriate Request Type: Make sure you're using a request type that
supports file uploads, such as POST or PUT.
d) Select Body Tab: In the request builder area, select the "Body" tab.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Postman will then send the request to the specified endpoint with the file attached.
Make sure your server-side application is configured to handle file uploads
appropriately.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
1. CRUD Operations:
a. Create a Spring Boot application to manage a simple todo list.
b. Implement functionality to add, retrieve, update, and delete todo items using
CRUD operations.
3. Exception Handling:
a. Introduce error handling in the todo list application to deal with common
exceptions like ResourceNotFoundException and
MethodArgumentNotValidException.
b. Implement custom exception handling to return appropriate error responses
with meaningful error messages.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Unit Testing: Unit testing focuses on testing individual units or components of the
application in isolation. In Spring Boot, you can use tools like JUnit and Mockito to
write unit tests for your service classes, controllers, repositories, and other
components.
• Integration Testing: Integration testing verifies that different parts of the
application work together correctly. In Spring Boot, you can use @SpringBootTest
annotation to bootstrap the entire application context for integration testing. You
can also use @WebMvcTest or @DataJpaTest to test specific layers of your
application in isolation.
• End-to-End Testing: End-to-End testing involves testing the entire application
from start to finish to ensure that all components interact correctly and produce
the desired output. In Spring Boot, you can use tools like Selenium for web UI
testing and tools like RestAssured for testing RESTful APIs.
• Mocking Dependencies: In many cases, you may need to mock dependencies
such as databases, external services, or collaborators during testing. Spring Boot
provides support for mocking with tools like Mockito and frameworks like Spring
Test.
• Test Profiles: Spring Boot allows you to define different configurations for
different environments using profiles. You can use this feature to set up different
configurations for testing, such as using an in-memory database (h2 database) for
integration tests.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Test Coverage: Aim for high test coverage to ensure that most of your code is
being exercised by tests. Tools like JaCoCo can help measure test coverage.
Overall, testing in Spring Boot involves writing comprehensive tests to ensure that your
application functions correctly, maintains stability, and meets the requirements of its
users. Proper testing practices contribute to the overall quality and reliability of your
software.
• Unit Testing: JUnit is primarily used for writing unit tests, which are tests that focus
on testing individual units or components of the code in isolation. A unit can be a
class, a method, or even a small piece of code. Unit tests verify that each unit of
code behaves as expected and produces the correct output for a given input.
• Test Annotations: JUnit provides annotations that are used to mark methods as
test methods and to configure the test environment. Some commonly used
annotations include:
• @Test: Marks a method as a test method.
• @Before: Indicates a method to be run before each test method.
• @After: Indicates a method to be run after each test method.
• @BeforeClass: Indicates a method to be run once before any test methods
in the class.
• @AfterClass: Indicates a method to be run once after all test methods in the
class.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Assertions: JUnit provides a set of assertion methods that are used to verify
expected outcomes in test methods. Assertions check whether the actual result
matches the expected result and report failures if they don't. Some commonly used
assertion methods include:
• assertEquals(expected, actual): Checks if two values are equal.
• assertTrue(condition): Checks if a condition is true.
• assertFalse(condition): Checks if a condition is false.
• assertNotNull(object): Checks if an object is not null.
• assertNull(object): Checks if an object is null.
• assertSame(expected, actual): Checks if two references point to the same
object.
• assertNotSame(expected, actual): Checks if two references do not point to
the same object.
• Parameterized Tests: JUnit supports parameterized tests, allowing you to run the
same test method with different sets of parameters. This is useful for testing the
same functionality with multiple input values.
• Exception Testing: JUnit provides built-in support for testing expected exceptions.
You can use annotations or try-catch blocks to assert that specific exceptions are
thrown during the execution of a test method.
• Test Suites: JUnit allows you to organize multiple test classes into test suites using
the @RunWith and @Suite annotations. Test suites enable you to run multiple tests
together as a single test suite.
• Integration with IDEs and Build Tools: JUnit integrates seamlessly with popular
Java IDEs like Eclipse, IntelliJ IDEA, and NetBeans, as well as build tools like Maven
and Gradle. IDEs provide built-in support for creating, running, and debugging
JUnit tests, making it easy to incorporate testing into the development workflow.
• Mocking and Dependency Injection: While JUnit itself does not provide mocking
capabilities, it is commonly used in conjunction with mocking frameworks like
Mockito, EasyMock, or PowerMockito for testing components with dependencies.
• Test Coverage: JUnit can be used in conjunction with code coverage tools like
JaCoCo to measure the percentage of code that is exercised by tests. Test coverage
helps identify areas of code that are not adequately covered by tests, enabling
developers to write more comprehensive test suites.
As per the present scenario, two version of JUnit are widely used in industries : JUnit4 &
JUnit5.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Best Training Institute
for Graduates
Online Live Classes Also Available
Amenities
Junit4
• JUnit 4 is a widely used testing framework for Java applications. It provides a simple
and effective way to write and execute automated tests for Java code.
• JUnit 4 is designed to support various testing scenarios, including unit tests,
integration tests, and more, making it suitable for testing all aspects of Java
applications.
• JUnit 4 provides a comprehensive and flexible framework for writing and executing
automated tests in Java applications.
• By using its features such as annotations, assertions, parameterized tests, exception
testing, and test suites, developers can ensure the reliability and correctness of
their Java code through rigorous testing practices.
1. Test Annotations: JUnit 4 uses annotations to mark methods as test methods and
to configure the test environment.
Example
import [Link].*;
@BeforeClass
public static void setUpClass() {
// Code to run once before any test methods in the class
}
@AfterClass
public static void tearDownClass() {
// Code to run once after all test methods in the class
}
@Before
public void setUp() {
// Code to run before each test method
}
@After
public void tearDown() {
// Code to run after each test method
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
@Test
public void testAddition() {
int result = [Link](3, 4);
[Link](7, result);
}
2. Assertions: JUnit 4 provides a set of assertion methods that are used to verify
expected outcomes in test methods. These assertion methods are part of the
[Link] class.
Example
import [Link];
import [Link];
public class CalculatorTest {
@Test
public void testAddition() {
int result = [Link](3, 4);
[Link](7, result);
}
@Test
public void testDivision() {
double result = [Link](10, 2);
[Link](5.0, result, 0.001); // Delta value for floating point
comparison
}
// More test methods...
}
In the example, assertEquals and assertSame methods are used to verify the expected
outcomes of addition and division operations.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
@RunWith([Link])
public class CalculatorParameterizedTest {
private final int a;
private final int b;
private final int expected;
public CalculatorParameterizedTest(int a, int b, int expected) {
this.a = a;
this.b = b;
[Link] = expected;
}
@[Link]
public static Collection<Object[]> data() {
return [Link](new Object[][] {
{1, 1, 2},
{2, 3, 5},
{5, 5, 10} });
}
@Test
public void testAddition() {
int result = [Link](a, b);
[Link](expected, result);
}
}
In the example, the CalculatorParameterizedTest class contains a parameterized
test method testAddition, which is run multiple times with different sets of
parameters specified by the @Parameters annotation.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
@Test(expected = [Link])
public void testDivideByZero() {
int result = [Link](10, 0);
}
}
In this example, the testDivideByZero method tests that an ArithmeticException is
thrown when dividing by zero.
5. Test Suites: JUnit 4 allows you to organize multiple test classes into test suites
using the @RunWith and @Suite annotations. Test suites enable you to run
multiple tests together as a single test suite.
Example
import [Link];
import [Link];
@RunWith([Link])
@[Link]({
[Link],
[Link],
[Link]
})
public class TestSuite {
// This class is empty; it is only used as a holder for the above annotations
}
In the example, the TestSuite class contains annotations to define a test suite that
includes CalculatorTest, CalculatorParameterizedTest, and ExceptionTest classes.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
1. First add the JUnit4 dependency to your maven project [Link] file
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
If the dependency for JUnit is available inside the [Link] file then only you need
to change the version as you are going to use JUnit4.
[Link]
package [Link];
public class Calculate {
public static int addition(int a, int b) {
return a+b;
}
public static int subtraction(int a, int b) {
return a-b;
}
public static int multiply(int a, int b) {
return a*b;
}
public static int divide(int a, int b) {
return a/b;
}
}
3. Create a class inside src/main/test to test the above class functionality. Make sure
that the classname must contain the name of class which is going to test (Calculate)
followed by word “Test”.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
package [Link];
import [Link];
import [Link];
public class CalculateTest {
@Test
public void additionTest()
{
int result= [Link](10,20);
int expectedResult=300;
[Link](expectedResult, result);
}
}
4. Run the above testclass using “JUnit Test” to check the runs, failures & Errors.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
If we want to perform some operations before & after the execution of all the test cases
then
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class CalculateTest {
@BeforeClass
public static void start() {
[Link]("test cases are going to be executed");
}
@AfterClass
public static void end() {
[Link]("test cases have been executed");
}
@Test
public void additionTest() {
[Link]("addition operation");
int result= [Link](10,20);
int expectedResult=30;
[Link](expectedResult, result);
}
@Test
public void subtractionTest() {
[Link]("subtraction operation");
int result= [Link](100,20);
int expectedResult=130;
[Link](expectedResult, result);
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
If we want to perform some operations before & after the execution of each test case
then
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link](expectedResult, result);
}
@Test
public void subtractionTest() {
[Link]("subtraction operation");
int result= [Link](100,20);
int expectedResult=130;
[Link](expectedResult, result);
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
package [Link];
import [Link];
import [Link];
@Test
public void subtractionTest()
{
[Link]("subtraction operation");
int result= [Link](100,20);
int expectedResult=130;
[Link](expectedResult, result);
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Here are some other commonly used annotations along with their purposes:
• @Ignore or @Disabled: Marks a test method to be ignored during test execution.
• @RunWith: Specifies a custom test runner to use for executing the tests.
• @Rule: Defines a rule to be applied to all test methods in a class or to a specific
test method.
• @Parameters: Indicates that the test method should be executed multiple times
with different parameter values.
• @Test(expected = [Link]): Specifies that the test method should throw
a specific exception, otherwise, it will fail.
• @DisplayName: Provides a custom display name for the test method.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
JUnit5
• JUnit 5 is a powerful and versatile testing framework for Java, designed to make
writing and running tests easier and more flexible.
• JUnit 5 builds upon the foundation of JUnit 4 while introducing new features and
enhancements to address the evolving needs of modern software development
practices.
• Its modular architecture, flexible extension model, and support for new Java
features make it a powerful choice for writing and running tests in Java
applications.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
JUnit Modules
JUnit 5 is composed of three main modules, each serving a specific purpose within the
testing ecosystem:
• JUnit Platform
• The JUnit Platform serves as the foundation for launching testing
frameworks on the JVM (Java Virtual Machine).
• It provides an API for test engines to discover, execute, and report on tests.
The platform is designed to be vendor-neutral and extensible, allowing
different testing frameworks to integrate seamlessly.
• Test engines can be written to support various testing frameworks, enabling
developers to choose the framework that best fits their needs while still
leveraging the benefits of the JUnit Platform.
• The test engine implementation is the responsibility of the JUnit Platform.
• JUnit Jupiter
• JUnit Jupiter is the programming model and extension model for writing
tests and extensions in JUnit 5.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• It provides annotations and APIs for defining test classes, test methods,
assertions, and extensions.
• JUnit Jupiter introduces several new features compared to JUnit 4, including
support for parameterized tests, nested tests, dynamic tests, and more
expressive assertions.
• It also offers an improved extension model based on annotations and
interfaces, allowing developers to extend the behavior of tests and the test
engine in a modular and flexible way.
• JUnit Vintage
• JUnit Vintage provides backward compatibility for running JUnit 3 and JUnit
4 tests on the JUnit 5 platform.
• It serves as a bridge between the old and new versions of JUnit, allowing
developers to migrate existing tests gradually without having to rewrite
them completely.
• JUnit Vintage supports running tests written in the JUnit 3 and JUnit 4 style,
including the use of annotations such as @Test, @Before, @After, etc.
• This ensures that legacy tests can be executed alongside tests written in the
JUnit Jupiter style within the same test suite.
To use JUnit5 in our java project to write the test cases, you need to inject the following
dependency in your maven project [Link] file
<!-- [Link] -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
But the limitation with above dependency is that it only provide the API, not the
implementation, so you need to use the junit-jupiter-engine dependency.
<!-- [Link] -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
For running parameterized test cases, you need to use the following dependency
<!-- [Link] -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
Assertions
• assertEquals(expected, actual): Asserts that two objects are equal.
• assertNotEquals(expected, actual): Asserts that two objects are not equal.
• assertTrue(condition): Asserts that a condition is true.
• assertFalse(condition): Asserts that a condition is false.
• assertNull(object): Asserts that an object is null.
• assertNotNull(object): Asserts that an object is not null.
• assertSame(expected, actual): Asserts that two objects refer to the same object.
• assertNotSame(expected, actual): Asserts that two objects do not refer to the same
object.
• assertArrayEquals(expectedArray, actualArray): Asserts that two arrays are equal.
• assertIterableEquals(expectedIterable, actualIterable): Asserts that two iterables are
equal.
• assertLinesMatch(expectedLines, actualLines): Asserts that two lists of strings are
equal, ignoring any differences in line terminators.
• assertThrows(exceptionType, executable): Asserts that an executable throws a
specific type of exception.
• assertTimeout(duration, executable): Asserts that an executable completes within
a specified duration.
• assertIterableEquals(expected, actual, [comparator]): Asserts that two iterables are
equal, optionally using a custom comparator.
• assertAll(executables...): Asserts that all of the provided executable assertions pass.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Annotations
• @Test: Marks a method as a test method.
• @BeforeEach: Indicates that the annotated method should be executed before
each test method.
• @AfterEach: Indicates that the annotated method should be executed after each
test method.
• @BeforeAll: Indicates that the annotated method should be executed once before
all test methods in the current class.
• @AfterAll: Indicates that the annotated method should be executed once after all
test methods in the current class.
• @DisplayName: Provides a custom display name for a test class or test method.
• @Disabled: Disables a test class or test method from execution.
• @ParameterizedTest: Indicates that the annotated method is a parameterized test.
• @RepeatedTest: Indicates that the annotated method should be repeated a
specified number of times.
• @Nested: Allows nesting test classes within another test class.
• @Tag: Tags a test class or test method with one or more labels.
• @Timeout: Specifies a timeout for a test method or test template method.
• @TestFactory: Indicates that the annotated method is a test factory for dynamic
tests.
• @DisplayNameGeneration: Specifies a custom display name generator for test
classes and test methods.
• @ExtendWith: Registers one or more extensions for a test class or test method.
• @RegisterExtension: Declares a field to be used as an extension instance.
• @TempDir: Provides a temporary directory that is created before each test method
execution.
• @TimeoutTest: Specifies a timeout for a specific test method.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Best Training Institute
for Graduates
Online Live Classes Also Available
Amenities
Mockito
• Mockito is a popular Java library used for creating and configuring mock objects
for testing purposes.
• It allows developers to simulate the behavior of external dependencies or
collaborators within their tests, enabling isolated unit testing.
• Mockito is particularly useful for Java and Spring Boot applications because it helps
in writing reliable and maintainable tests by mocking external dependencies and
focusing on testing individual units of code in isolation.
• Mockito is a valuable tool for Java and Spring Boot developers, providing them
with the means to write effective unit tests that are focused, reliable, and
maintainable.
• By using Mockito to mock dependencies and isolate units under test, developers
can ensure the quality and correctness of their code while promoting best practices
in software testing.
• In simple words, a mock object returns a dummy data and avoids external
dependencies.
• It uses java reflection API to create objects.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Reflection API
• The Reflection API allows you to examine or modify the runtime behavior of
applications running on the Java Virtual Machine (JVM).
• It provides a way to inspect classes, interfaces, fields, and methods at runtime, as
well as instantiate objects, invoke methods, and access or modify fields
dynamically, without having direct compile-time knowledge of the classes
involved.
• This ability to introspect and manipulate classes and objects at runtime makes the
Reflection API a powerful and flexible tool, often used in frameworks, libraries, and
tools that require dynamic behavior.
• Reflection provides a way to inspect and manipulate classes and objects
dynamically, offering flexibility and power but also requiring caution due to its
potential impact on performance and security.
• It's commonly used in frameworks like Spring and Hibernate, as well as in various
testing and debugging tools.
• Reflection API has the capability to dynamically generate proxies for interfaces and
classes. This feature enables the creation of dynamic proxy instances that intercept
method calls and provide custom behavior before or after invoking the actual
methods of the target object.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Class Objects: In the Reflection API, everything starts with Class objects, which
represent classes or interfaces in Java. These Class objects can be obtained in
various ways, such as using the .class syntax, [Link](), or by calling
.getClass() on an object instance.
• Inspecting Classes: Reflection allows you to inspect the structure of classes at
runtime. You can access information about fields, methods, constructors,
annotations, and more using methods provided by the Class class.
• Accessing Fields and Methods: Reflection enables you to access fields and
methods of classes dynamically, even private ones. You can get, set, or invoke fields
and methods using Field and Method objects, respectively.
• Dynamic Instantiation: Reflection enables you to instantiate objects of classes
dynamically, without knowing their type at compile time. You can create new
instances using constructors obtained through reflection.
• Dynamic Invocation: Reflection allows you to invoke methods of classes
dynamically, without knowing their signatures at compile time. You can invoke
methods with specific arguments using reflection.
package [Link];
import [Link];
import [Link];
import [Link];
class Employee {
private String name;
private int age;
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]("Hello, my name is " + name + " and I am " + age + " years
old.");
}
}
import [Link];
class ParameterizedMethodExample {
public static void main(String[] args) throws Exception {
// Get the Class object for the class containing the method
Class<?> cls = [Link];
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
As Reflection API is capable to dynamically generate proxies for interfaces and classes
then here is the overview of dynamic proxies and their benefits:
• Interface Proxies: With reflection, you can create a proxy instance that
implements one or more interfaces. This proxy intercepts method calls made to
those interfaces and allows you to provide custom behavior.
• Method Invocation Handling: Dynamic proxies give you the ability to intercept
method invocations on the proxy object and perform additional logic before or
after invoking the actual method on the target object.
• Aspect-Oriented Programming (AOP): Dynamic proxies are commonly used in
AOP frameworks to implement cross-cutting concerns such as logging, security,
and transaction management. By intercepting method calls, AOP proxies can inject
additional behavior into the application without modifying the original source
code.
• Decoupling: Dynamic proxies help in decoupling the concerns of the application.
They allow you to separate the core business logic from cross-cutting concerns,
resulting in cleaner and more maintainable code.
• Lazy Initialization: Dynamic proxies can be used for lazy initialization of objects.
Instead of creating an instance of a heavyweight object upfront, you can defer its
creation until the first method call on the proxy, improving performance by
avoiding unnecessary object creation.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Example : demonstrating how to create a dynamic proxy using the Reflection API
import [Link];
import [Link];
import [Link];
interface Hello {
void sayHello();
}
class HelloImpl implements Hello {
public void sayHello() {
[Link]("Hello, World!");
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
In the example:
• We define an interface Hello and a class HelloImpl that implements the interface.
• We create an InvocationHandler implementation MyInvocationHandler that
intercepts method calls on the proxy.
• We create a dynamic proxy instance using [Link](), passing the
interface Hello, the class loader, and the InvocationHandler.
• When the sayHello() method is invoked on the proxy, the invoke() method of the
InvocationHandler is executed, allowing us to perform custom logic before and
after invoking the actual method on the target object.
Dynamic proxies provide a flexible mechanism for adding behavior to objects at runtime,
making them a powerful tool for building extensible and modular applications.
So, if we want to perform Unit testing using Mockito then the following dependencies
would be required:
If you are using JUnit5 then you also need to inject the following dependency
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Exercise:
• First create a class Employee
public class Employee
{
private EmployeeDetails employeeDetails;
Now create a test class to test the above classes and interfaces
So, If we run the above code then we will get NullPointerException because we don't have
any value to Test.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
So to overcome this problem you can create a stub for Testing the module
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
The above concept get failed when you will have some additional functionalities in the
EmployeeDetails interface in future so to manage these types of operations would be
complex & you need to manually make changes inside the implementation class to
provide the functionality
In that case you need to use the Mockito to mock the objects.
import [Link];
import [Link];
import [Link];
@Test
public void getEmployeeIDTest()
{
//Mocking Object
EmployeeDetails employeeDetails=[Link]([Link]);
Employee emp=new Employee(employeeDetails);
// To declare that when the getEmployeeDetails method get called then it
will return 20.
[Link]([Link]()).thenReturn(200);
int result=[Link]();
[Link](20,result);
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Mockito Annotations
Mockito is a popular Java framework used for creating and configuring mock objects.
Mockito provides several annotations that help in writing unit tests effectively.
In previous example we had used the below statement to create the mock object of the
interface EmployeeDetails.
EmployeeDetails employeeDetails=[Link]([Link]);
So, if you don’t want to do this then you can simply use the @Mock Annotation to create
the mock object of the same interface.
& we had also used the below statement to inject the mock object into the Employee
Employee emp=new Employee(employeeDetails);
So, if you don’t want to do this then you can use @InjectMocks Annotation.
To use the Mockito related annotations, you need to initialize the MockitoAnnotations
using method [Link](). The method must get executed before the
execution of every test case or all the test cases of the test class.
[Link]
public class Employee
{
private EmployeeDetails employeeDetails;
public Employee(EmployeeDetails employeeDetails) {
[Link]=employeeDetails;
}
public int getEmployeeID() {
int id = [Link]();
[Link]("The Employee Id is : "+id);
return id;
}
}
[Link]
public interface EmployeeDetails{
public int getEmployeeDetails();
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Mock
EmployeeDetails employeeDetails;
@InjectMocks
Employee employee;
@BeforeEach
public void init() {
[Link](this);
}
@Test
public void getEmployeeIDTest()
{
[Link]([Link]()).thenReturn(20);
int result=[Link]();
[Link](20,result);
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@ExtendWith([Link])
public class EmployeeTest{
@Mock
EmployeeDetails employeeDetails;
@InjectMocks
Employee employee;
@Test
public void getEmployeeIDTest() {
[Link]([Link]()).thenReturn(20);
int result=[Link]();
[Link](20,result);
}
}
With the setup, you don't need to call [Link](this) in your setup
method. The MockitoExtension will take care of initializing mocks and spies for you. This
approach is specifically for JUnit 5. If you're using JUnit 4, then MockitoJUnitRunner or
[Link](this) are the options available.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Mockito can mock interfaces and abstract classes without any issues.
[Link]
import [Link];
import [Link];
import [Link];
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import static [Link];
@ExtendWith([Link])
public class CollectionOperationTest {
@Mock
private List<String> listMock;
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
@Mock
private Set<String> setMock;
@Mock
private Map<Integer, String> mapMock;
@Test
public void testProcessList() {
when([Link]()).thenReturn(5);
CollectionOperation collectionOperation = new CollectionOperation();
int result = [Link](listMock);
[Link](5, result);
}
@Test
public void testProcessSet() {
when([Link]()).thenReturn(3);
CollectionOperation collectionOperation = new CollectionOperation();
int result = [Link](setMock);
[Link](3, result);
}
@Test
public void testProcessMap() {
when([Link]()).thenReturn(10);
CollectionOperation collectionOperation = new CollectionOperation();
int result = [Link](mapMock);
[Link](10, result);
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
@Autowired
private EmployeeRepository employeeRepository;
public Employee save(Employee employee) {
return [Link](employee);
}
public List<Employee> findAll() {
return [Link]();
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Write unit tests using JUnit5 and Mockito to test the service and controller
classes.
EmployeeServiceTest
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@ExtendWith([Link])
class EmployeeServiceTest {
@InjectMocks
private EmployeeService employeeService;
@Mock
private EmployeeRepository employeeRepository;
@Test
void saveEmployeeTest() {
Employee employee = new Employee();
[Link]("Neha Mittal");
[Link]("Gurugram");
[Link]([Link]([Link]([Link]))).the
nReturn(employee);
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
@Test
void findAllEmployeesTest() {
List<Employee> employees = new ArrayList<>();
[Link](new Employee());
[Link](new Employee());
[Link]([Link]()).thenReturn(employees);
[Link](allEmployees);
[Link](2, [Link]());
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
EmployeeService
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Service
public class EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
public Employee save(Employee employee) {
return [Link](employee);
}
public List<Employee> findAll() {
return [Link]();
}
public Optional<Employee> findById(String id) {
return [Link](id);
}
public Employee updateEmployee(String id, Employee updatedEmployee) {
Optional<Employee> existingEmployeeOptional =
[Link](id);
if (![Link]()) {
throw new ResourceNotFoundException("Employee not found with id: " +
id);
}
Employee existingEmployee = [Link]();
[Link]([Link]());
[Link]([Link]());
return [Link](existingEmployee);
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
package [Link];
import [Link];
import [Link];
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@PostMapping
public ResponseEntity<Employee> createEmployee(@RequestBody Employee
employee) {
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
return [Link]([Link](employee));
}
@GetMapping
public ResponseEntity<List<Employee>> getAllEmployees() {
return [Link]([Link]());
}
@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable String id) {
return [Link]([Link](id).orElseThrow(() ->
new ResourceNotFoundException("Employee not found with id: " + id)));
}
@PutMapping("/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable String id,
@RequestBody Employee updatedEmployee) {
return [Link]([Link](id,
updatedEmployee));
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteEmployee(@PathVariable String id) {
[Link](id);
return [Link]().build();
}
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import static [Link].*;
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
@ExtendWith([Link])
class EmployeeServiceTest {
@InjectMocks
private EmployeeService employeeService;
@Mock
private EmployeeRepository employeeRepository;
@Test
void findEmployeeByIdTest() {
String id = "1";
Employee employee = new Employee();
[Link](id);
[Link]("Shweta Sharma");
[Link]("Noida");
[Link]([Link](id)).thenReturn([Link](employee));
Optional<Employee> foundEmployee = [Link](id);
assertTrue([Link]());
[Link]("Shweta Sharma", [Link]().getName());
[Link]("Noida", [Link]().getCity());
}
@Test
void updateEmployeeTest() {
String id = "1";
Employee existingEmployee = new Employee();
[Link](id);
[Link]("Shweta Sharma");
[Link]("Noida");
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link](result);
[Link]("Tarun Gupta", [Link]());
[Link]("Tundla", [Link]());
}
@Test
void deleteEmployeeTest() {
String id = "1";
Employee employee = new Employee();
[Link](id);
[Link]("Shweta Sharma");
[Link]("Agra");
[Link]([Link](id)).thenReturn([Link](employee));
[Link](id);
[Link](employeeRepository, [Link](1)).deleteById(id);
}
@Test
void updateNonExistentEmployeeTest() {
String id = "1";
Employee updatedEmployee = new Employee();
[Link](id);
[Link]("Shweta Sharma");
[Link]("Noida");
[Link]([Link](id)).thenReturn([Link]());
[Link]([Link], () -> {
[Link](id, updatedEmployee);
});
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Best Training Institute
for Graduates
Online Live Classes Also Available
Amenities
Thymeleaf
• Thymeleaf is a modern server-side Java template engine for web and standalone
environments.
• It is extensively used in the Spring Framework for building web applications.
• The significance of using Thymeleaf in a Spring Boot application lies in its simplicity,
power, and seamless integration with the Spring ecosystem, which enables
developers to build robust and dynamic web applications efficiently.
• Thymeleaf generates HTML views for web applications.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Learning Curve: While Thymeleaf's syntax is similar to HTML, mastering its more
advanced features and understanding its integration with Spring Boot can require
some learning time for developers who are new to it.
• Performance: Thymeleaf is a server-side template engine, meaning that rendering
templates happens on the server. In some cases, this can lead to performance
issues, especially if complex templates are used or if large amounts of data need
to be processed.
• Limited JavaScript Support: Thymeleaf is primarily designed for server-side
rendering, so its support for client-side JavaScript frameworks like Angular or React
is limited. Integrating such frameworks with Thymeleaf templates can sometimes
be challenging.
• Debugging: Debugging Thymeleaf templates can be more challenging compared
to debugging plain HTML or JavaScript code. Syntax errors or incorrect expressions
in templates might not be immediately obvious, requiring careful inspection.
• IDE Support: While most popular IDEs provide support for Thymeleaf, the level of
support might not be as robust as for other technologies like JSP or plain HTML.
• Version Compatibility: Ensuring compatibility between different versions of
Thymeleaf, Spring Boot, and other libraries in the project stack can sometimes be
a challenge, especially when upgrading dependencies.
• Resource Consumption: Thymeleaf processing consumes server resources,
particularly CPU and memory. In high-traffic applications, this can impact server
performance and scalability.
• Caching: Caching rendered templates effectively can be challenging, especially in
distributed environments or when dealing with dynamic content. Improper caching
strategies can lead to stale or inconsistent data being displayed to users.
Despite these challenges, Thymeleaf remains a popular choice for templating in Spring
Boot applications due to its ease of use, integration with Spring ecosystem, and powerful
features for dynamic content generation. With careful planning and attention to best
practices, these challenges can be mitigated effectively.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Thymeleaf Features
Thymeleaf offers a wide range of features that make it a popular choice for templating in
Spring Boot and other Java-based web applications.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
These features, along with Thymeleaf's ease of use and seamless integration with the
Spring ecosystem, make it a powerful tool for building dynamic and maintainable web
applications in Java.
Thymeleaf generates HTML views for web applications through a process called template
processing.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Client-side Display: The web browser receives the HTML response and renders it
to the user. The user sees the web page with the dynamically generated content
displayed as intended.
Throughout this process, Thymeleaf seamlessly integrates with the Spring ecosystem,
allowing developers to use it as the view layer in Spring MVC applications. Thymeleaf's
expression language, template composition features, and integration with Spring
components make it a powerful tool for generating dynamic HTML views for web
applications.
Thymeleaf Expressions
Thymeleaf expressions are used within Thymeleaf templates to dynamically evaluate and
manipulate data. These expressions are written using Thymeleaf's expression language
(often abbreviated as "th:"). Thymeleaf expressions allow you to access data from the
model, perform logical operations, iterate over collections, and more.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
These expressions are evaluated by Thymeleaf at runtime, and the resulting values are
rendered into the HTML output. Thymeleaf expressions make it easy to create dynamic
and data-driven web pages in Spring Boot and other Java-based web applications.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
@Controller
public class AppController {
@GetMapping("/emp")
public String getEmployee(Model model) {
[Link]
<!DOCTYPE html>
<html lang="en" xmlns:th="[Link]
<head>
<meta charset="UTF-8">
<title>Employee Details</title>
</head>
<body>
<h1>Employee Details</h1>
<p th:text="'First Name: ' + ${[Link]}"></p>
<p th:text="'Last Name: ' + ${[Link]}"></p>
<p th:text="'Email: ' + ${[Link]}"></p>
</body>
</html>
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
public class Employee {
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Best Training Institute
for Graduates
Online Live Classes Also Available
Amenities
[Link]
import [Link];
import [Link];
import [Link];
@Controller
public class AppController {
@GetMapping("/")
public String homePage(Model model) {
int number = 10;
[Link]("number", number);
return "index";
}
}
[Link]
<!DOCTYPE html>
<html xmlns:th="[Link]
<head>
<meta charset="UTF-8">
<title>Thymeleaf Demo</title>
</head>
<body>
<div th:if="${number > 0}">
<p>Number is positive</p>
</div>
<div th:else>
<p>Number is non-positive</p>
</div>
</body>
</html>
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
import [Link];
import [Link];
import [Link];
@Controller
public class AppController {
@GetMapping("/")
public String homePage(Model model) {
int option = 2; // Assuming option value
[Link]("option", option);
return "index";
}
}
[Link]
<!DOCTYPE html>
<html xmlns:th="[Link]
<head>
<meta charset="UTF-8">
<title>Thymeleaf Demo</title>
</head>
<body>
<div th:switch="${option}">
<p th:case="1">Option 1 selected</p>
<p th:case="2">Option 2 selected</p>
<p th:case="3">Option 3 selected</p>
<p th:case="*">Default option selected</p>
</div>
</body>
</html>
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
import [Link];
import [Link];
import [Link];
@Controller
public class AppController {
@GetMapping("/")
public String homePage(Model model) {
String[] fruits = {"Apple", "Banana", "Orange"};
[Link]("fruits", fruits);
return "index";
}
}
[Link]
<!DOCTYPE html>
<html xmlns:th="[Link]
<head>
<meta charset="UTF-8">
<title>Thymeleaf Demo</title>
</head>
<body>
<h2>Fruits List</h2>
<ul>
<li th:each="fruit : ${fruits}" th:text="${fruit}"></li>
</ul>
</body>
</html>
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
import [Link];
import [Link];
import [Link];
@Controller
public class AppController {
@GetMapping("/")
public String homePage(Model model) {
[Link]("greeting", "Hello, World!");
[Link]("showGreeting", true);
return "index";
}
}
[Link]
<!DOCTYPE html>
<html xmlns:th="[Link]
<head>
<meta charset="UTF-8">
<title>Thymeleaf Demo</title>
</head>
<body>
<div th:if="${showGreeting}">
<h1 th:text="${greeting}"></h1>
</div>
</body>
</html>
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Example : Accessing a specific element from a collection (List) in Thymeleaf using Spring Boot
[Link]
public class Item {
private String name;
private double price;
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Controller
public class AppController {
@GetMapping("/")
public String homePage(Model model) {
[Link]("items", itemList);
return "index";
}
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
<html xmlns:th="[Link]
<head>
<meta charset="UTF-8">
<title>Thymeleaf Demo</title>
</head>
<body>
<h2>Items List</h2>
<table border="1">
<tr>
<th>Name</th>
<th>Price</th>
</tr>
<tr th:each="item : ${items}">
<td th:text="${[Link]}"></td>
<td th:text="${[Link]}"></td>
</tr>
</table>
</body>
</html>
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Example: Dynamically modify HTML attributes based on data in Thymeleaf using Spring
Boot
[Link]
import [Link];
import [Link];
import [Link];
@Controller
public class AppController {
@GetMapping("/")
public String homePage(Model model) {
boolean isLoggedIn = true;
[Link]("isLoggedIn", isLoggedIn);
return "index";
}
}
[Link]
<!DOCTYPE html>
<html xmlns:th="[Link]
<head>
<meta charset="UTF-8">
<title>Thymeleaf Demo</title>
</head>
<body>
<ul>
<li><a th:href="@{${isLoggedIn} ? '/dashboard' : '/login'}">Go to
Dashboard</a></li>
</ul>
</body>
</html>
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
import [Link];
import [Link];
import [Link];
@Controller
public class AppController {
@GetMapping("/")
public String homePage(Model model) {
boolean isActive = true;
[Link]("isActive", isActive);
return "index";
}
}
[Link]
<!DOCTYPE html>
<html xmlns:th="[Link]
<head>
<meta charset="UTF-8">
<title>Thymeleaf Demo</title>
<style>
.active {
color: green;
font-weight: bold;
}
</style>
</head>
<body>
<p th:class="${isActive} ? 'active' : ''">This paragraph is dynamically styled
based on isActive attribute.</p>
</body>
</html>
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
import [Link];
import [Link];
@Controller
public class AppController {
@GetMapping("/")
public String homePage() {
return "index";
}
@GetMapping("/about")
public String aboutPage() {
return "about";
}
}
[Link]
<!DOCTYPE html>
<html xmlns:th="[Link]
<head>
<meta charset="UTF-8">
<title>Header Fragment</title>
</head>
<body>
<header>
<h1>My Website</h1>
<nav>
<ul>
<li><a th:href="@{/}">Home</a></li>
<li><a th:href="@{/about}">About</a></li>
</ul>
</nav>
</header>
</body>
</html>
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
[Link]
<!DOCTYPE html>
<html xmlns:th="[Link]
<head>
<meta charset="UTF-8">
<title>Home Page</title>
</head>
<body>
<div th:replace="fragments/headerFragment :: header"></div>
<h2>Hello, Dear Students</h2>
<!-- Rest of the content -->
</body>
</html>
[Link]
<!DOCTYPE html>
<html xmlns:th="[Link]
<head>
<meta charset="UTF-8">
<title>About Page</title>
</head>
<body>
<div th:replace="fragments/headerFragment :: header"></div>
<h2>About Us Page</h2>
<!-- Rest of the content -->
</body>
</html>
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Thymeleaf and JSP (JavaServer Pages) are both technologies used for server-side
rendering of dynamic web pages in Java-based web applications, but they have some key
differences:
• Syntax
Thymeleaf:
Thymeleaf uses a natural syntax that resembles HTML, making it easier for
front-end developers to work with. Thymeleaf templates are designed to be
readable and writable, with HTML-like attributes prefixed with th: for
Thymeleaf-specific functionality.
JSP:
JSP uses a syntax that mixes Java code with HTML, which can sometimes
lead to a less clean separation of concerns between presentation and
business logic.
• Execution Model
Thymeleaf:
Thymeleaf templates are parsed and processed on the server-side before
being sent to the client's browser. Thymeleaf provides powerful server-side
rendering capabilities, making it suitable for generating dynamic content
and interacting with server-side data.
JSP:
JSP pages are translated into servlets and compiled into Java bytecode on
the server-side. The resulting servlets handle HTTP requests and generate
HTML dynamically before sending it to the client. JSP pages are typically
compiled once and cached for subsequent requests.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Expression Language
Thymeleaf:
Thymeleaf provides its own expression language (Thymeleaf Standard
Dialect), which offers features like variable access, iteration, conditionals,
and more. Thymeleaf expressions are designed to be simple and powerful,
allowing for easy manipulation of data within templates.
JSP:
JSP uses JavaServer Pages Expression Language (EL), which provides similar
functionality to Thymeleaf expressions but with a syntax that is more closely
tied to Java.
Overall, both Thymeleaf and JSP are capable technologies for server-side rendering in
Java web applications, but Thymeleaf is often preferred for its cleaner syntax, better
integration with Spring Boot, and more modern approach to templating.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Best Training Institute
for Graduates
Online Live Classes Also Available
Amenities
Microservices
• Microservices are a software development approach where a large application is
built as a collection of loosely coupled services.
• Each service is focused on a specific business capability and can be developed,
deployed, and scaled independently.
• Microservices architecture can help organizations build more scalable, flexible, and
resilient applications that can adapt to changing business requirements.
• Microservices play a crucial role in large-scale applications due to their ability to
break down complex systems into smaller, more manageable parts.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Here are some key ways in which microservices contribute to the success of large-scale
applications:
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Monolithic Architecture
Distributed Architecture
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Overall, while microservices offer many advantages in a distributed environment, they are
not a one-size-fits-all solution and should be carefully considered based on the specific
requirements and constraints of the application being developed.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Developing and deploying microservices for a distributed architecture involves below key
steps:
• Define Service Boundaries: Identify the different parts of your application that
can be broken down into separate services. Each service should have a well-defined
boundary and responsibility.
• Choose Communication Protocols: Decide on the communication protocols that
will be used between services. Common options include HTTP/REST, messaging
queues (e.g., RabbitMQ, Kafka), and gRPC.
• Design APIs: Define the APIs that will be used by each service to communicate
with other services. This includes specifying the data formats (e.g., JSON, XML) and
the endpoints for each service.
• Implement Services: Develop each microservice using the appropriate
technologies and frameworks. Each service should be self-contained and
responsible for a specific business function.
• Containerize Services: Use containerization technology (e.g., Docker) to package
each microservice along with its dependencies. This ensures that the service can
run consistently across different environments.
• Deploy Services: Deploy each microservice to your chosen deployment
environment (e.g., on-premises, cloud). Use orchestration tools (e.g., Kubernetes,
Docker Swarm) to manage and scale your services.
• Monitor and Manage: Implement monitoring and logging to track the
performance and health of your microservices. Use tools like Prometheus, Grafana,
and ELK stack for monitoring and logging.
• Handle Failures: Implement strategies to handle failures gracefully, such as
retrying failed requests, circuit breaking, and fallback mechanisms.
• Scale Services: Use auto-scaling features provided by your deployment
environment to scale your services based on demand.
• Update Services: Implement a strategy for updating your services, such as blue-
green deployments or canary releases, to minimize downtime and impact on users.
• Security: Implement security best practices, such as authentication, authorization,
and encryption, to protect your microservices from unauthorized access and
attacks.
• Testing: Perform thorough testing of your microservices, including unit tests,
integration tests, and end-to-end tests, to ensure they work correctly and meet the
required quality standards.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
• Setting Up Your Development Environment: Ensure you have Java and an IDE
(such as IntelliJ IDEA or Eclipse) installed. You'll also need Maven or Gradle for
dependency management.
• Creating a New Spring Boot Project: You can create a new Spring Boot project
using Spring Initializr or STS. Visit [Link], select the dependencies you need
(e.g., Spring Web, Spring Data JPA), and generate the project.
• Creating Your First Microservice: Once you have your project set up, you can
start creating your microservices. For example, let's create a simple RESTful service
for managing products.
@RestController
@RequestMapping("/products")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping
public List<Product> getAllProducts() {
return [Link]();
}
@PostMapping
public ResponseEntity<Product> createProduct(@RequestBody Product
product) {
Product createdProduct = [Link](product);
return [Link]([Link]("/products/" +
[Link]())).body(createdProduct);
}
// Other CRUD operations
}
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Spring Boot provides many features to simplify the development of microservices, such
as auto-configuration, embedded servers (like Tomcat or Jetty), and production-ready
metrics and health checks. It also integrates well with other Spring projects, such as Spring
Cloud, for building distributed systems.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Example : To fetch employee details from a MongoDB database using Spring Boot
• Create a new Spring Boot project and through [Link], select the following
dependencies:
▪ Spring Web
▪ Spring Data MongoDB
▪ Generate the project and import it into your IDE.
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
Learn-2-Earn Labs - Best Institute for Job-Oriented Training Programs, Startup Guidance & Innovation
Online Live Classes Available | Best Training Curriculum | for more information, visit – [Link]
LEARN-2-EARN LABS TRAINING INSTITUTE
F-4, First Floor, Anna Icon Complex,
near Kargil Petrol Pump, Sikandra-Bodla Road,
Sikandra, Agra, Uttar Pradesh, India
Website : [Link]