0% found this document useful (0 votes)
260 views19 pages

Spring Boot

This document provides information about Spring Boot including its configuration, dependencies, annotations used, CRUD operations, and other concepts related to developing APIs with Spring Boot. It discusses initializing Spring projects, connecting to databases, implementing controllers and services, and deploying projects.

Uploaded by

kadalipavithra
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
260 views19 pages

Spring Boot

This document provides information about Spring Boot including its configuration, dependencies, annotations used, CRUD operations, and other concepts related to developing APIs with Spring Boot. It discusses initializing Spring projects, connecting to databases, implementing controllers and services, and deploying projects.

Uploaded by

kadalipavithra
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 19

Spring Boot

Spring is open source s/w.


Now owned by: piotal.

Configuration :
Create a folder “sprongbootApplication” within that create one more folder
“backendApplication” this is for workspace. got to your downloads there you
already dowmloaded the spring boot application copy and past the
application in sprongbootApplication folder right click open (always open
with java easy ). There you will get sts-4.20.1.RELEASE folder. Delete the zip
file.

Spring initializer: even if create spring starter project it refers the


website.
Got to website “start.spring.io”
Version : latest one (do not choose snapshot)
GroupId : always the company name.
ArtifactId : projectName
Project: maven.
Language: java
Add dependency
Drivers for database: Spring data JPA.
Spring web:
Lombock- avoids the un necessary code like setter and getter.
Download the spring initializer project and extract in any folder
then import in eclipse or spring application

Initial point :
@SpringBootApplication --- It scans the compoents within the
package.
It contains 3 annotations
1. @SpringBootConfiguration
2. @EnableAutoConfiguration
3. @ComponentScan

How to add the new dependency in the existing project?


1. Go to spring initializer/ mvn repository  explore-> copy and
add.
2. Right click on project , go to spring Add starter , search
dependency, select the particular check box. Click on right to
left arrow marks on left side of the window.

Application Property file:


To change the port number, go to application property file Type-
“spring. port=8085” (port number)

@GetMapping :

@GetMapping is used to map HTTP GET requests to specific handler


methods in your controller class. @GetMapping can also handle
request parameters. @GetMapping to handle path variables in the
URL. For example, @GetMapping("/user/{id}")
@Pathvariable :
IT is used to provide the input value. From the http request.
If parameter and name of the getmaping value both are same no
need to specify the name in braces beside @pathvariable.
Ex:
@Getmapping(“/num”)
Public int basicMathsController ( @Pathvariable(“num”) int
number)
{
Int fact =1;
For(int i=number;i>=1;i++)
{
Fact=fact*i;
}return fact;
}
Calling the method :- http://localhost:8085/number/5

Multiple path variables :


@GetMapping(“/{x}/{y}”)
Public int multiplication(@pathvariable(“x”) int num1, @pathvariable
(“y”) int num2)
{
return (x*y);
}
CRUD OPERATIONS :
CRUD operations refer to the fundamental actions that can be performed on data. CRUD
stands for Create, Read, Update, and Delete.

C - Create : Deals with adding new records to a database. Can be done


by POST method

For example, when adding a new user to a system, you might create a
POST endpoint that receives user data in the request body, processes it,
and saves it to the database.

R – Read: Reading data involves retrieving existing records from the database or storage
system. We can use repository methods or custom queries to fetch data based on specific
criteria.

For example, to retrieve a user by their ID, you might create a GET endpoint that accepts the
ID as a path variable.

U – Update: means modifying existing records in the database. Can be done by


either by using repository methods or custom update queries.

For example, to update a user's information, you might create a PUT endpoint that
receives the updated user data and applies the changes to the corresponding record
in the database.

D – Delete: Means removing records from the database


By Delete method.

Application properties : connecting database


spring.datasource.url=jdbc:mysql://localhost:3306/
cruidOperations? useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=root

#heibernate properties
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true  will show the message in console
weather the database is created or not.
logging.level.org.springframework=debug  it will display the extra
information or details

Dept service Level : this is architech

Download postman tool


https://www.postman.com/downloads/

Why there are different layers in api?


In realtime many people develops the application, and interface or
service is designed by architecht,
For the huge projects it is difficutlt to find the particular methods ,
code will confuse.
what is jar file?
Jar file is a package file format typically used to aggregate many Java class files, metadata,
and resources (such as images, text files, etc.) into a single file. JAR files are platform-
independent, can be executed on any system.

Why we use maven project in spring?


Maven manages jars needed for the application
What is Dependency Injuction?
Types
Constructor based : dependencies are set by creating the bean using
its constructor.
@Autowired
public GameRunner(Mariogame game) {

this.game=game;
}
Setter based: dependencies are set by calling setters on your bean.
Field based: no setter no constructor , dependencies are injucted
using reflection.
Here we use @Autowired annotation
@Autowired
private GamingConsole game;
Spring boot
Steps to develop API
1.create entity class
2.provide the application properties and create entity class.
3.once run the project weather it is connected/ running properly or
not .
4. create a package repository and
This repository should implement the JPArepository interface
5.Create a package service
In this package create a corresponding service interface.
Level 4: create a package service implementation
In this package create a class corresponding serviceimpl, this class
should implement service interface. Foe this class we must provide
@Service annotation.
Level 5: create a package controller.
In this package

post man:

Post: create a collection- >new request-> select body-> select row-> insert the values corresponding to

entity attributes. -> select post method ->write corresponding url to your

Status code:

201Created – for posting the records

202 Accepted
404 – not found

create 5 packages
1. Entity: classes (@table, @Entity)
2. Repository:
3. Service
4. serviceImpl: @services
5. Controller: RESTCONTROLLERS
Jpa : packaging the project to deploy in server
Dependencies
Spring Web : Build web, including RESTful, applications using Spring MVC. Uses
Apache Tomcat as the default embedded container.

Lombok :
Spring data JPA :
My sql driver
Spring boot dev tools
Spring security

2.Application Properties
server.port=8095

spring.datasource.url=jdbc:mysql://localhost:3306/
sapnapharma?useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=root

# Hibernate Properties
spring.jpa.hibernate.ddl-auto=update
server.error.include-binding-errors=always

Exception Handling:
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {

private static final long serialVersionUID =1L;


private String resourceName;
private String feildName;
private Object feildValue;

public ResourceNotFoundException(String resourceName, String


feildName, Object feildValue) {
super (String.format("%s resource has not found with %s:
'%s'",resourceName,feildName,feildValue));
this.resourceName = resourceName;
this.feildName = feildName;
this.feildValue = feildValue;
}

public String getResourceName() {


return resourceName;
}

public String getFeildName() {


return feildName;
}

public Object getFeildValue() {


return feildValue;
}

// ServiceImple class
@Override
public Department getOneDepartment(long id) {

Department existingDept=
deptRepository.findById(id).orElseThrow(()->
new ResourceNotFoundException("Department", "id", "id"));

return existingDept;

example 2:
Swagger –It is an open api
Got to web : https://springdoc.org/ ->getting started
Copy and past the dependency in pom.xml file
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.4.0</version>
</dependency>

Update the pom.xml file (right click on pom.xml ->maven->update


project->forced update)
Type url in browser :http://localhost/swagger-ui/index.htmp

 How to execute spring boot project in command prompt?


First Make sure maven is installed and configured
1.Open command prompt in project
Command: mvn clean package- it generates jar file in target
folder of your project
3. In target folder open command prompt enter command
Java –jar StudyCenterManagement-0.0.1-SNAPSHOT.jar (this is
you jar file name)

how to deploy project(war file) in tomcat


server?
create a srarter/dynamic project make sure it is running properly;
 generate war file: in your project- >right click on pom.xml file -> run
ass -> maven install
 it generates 2 war files in ->project (ex: dept.)-> target folder -> war
files
 copy the first one war file and past in tomcat servers webapps folder.
here open cmd and write a command “startup” -> tomcat server will
run -> you can see spring icon there to make sure your project is
running properly. If it is not running check the tomcat server version
and install latest one.
 open browser -> write  http://localhost:8080/warfilename/swagger-
ui/index.html

*Time Stamp :
created at, modified at: @CreationTimestamp, @UpdateTimestamp

Validations :
Add the annotation -- @Validation

Example:
@Table
@Setter
@Getter
public class Greeting {

@NotNull
@NotBlank
@NotEmpty
private String mgs;

@NotNull
@NotBlank
@NotEmpty
private String from;

@NotNull
@NotBlank
@NotEmpty
private String to;
}

//controller class

@RestController
@RequestMapping("/api/v1/mgs")
@RequiredArgsConstructor
public class MsgController {

private final MsgServiceImpl msgServiceImpl;

@PostMapping("/post")
public ResponseEntity<String> createGreeting(@RequestBody
@Valid Greeting greeting, BindingResult bindingResult)
{

if(bindingResult.hasErrors())
{
return new ResponseEntity<String>(" please check the
details and fields properly felids must not null or
blanck",HttpStatus.BAD_REQUEST) ;
}

final String greetinMsg =


msgServiceImpl.saveGreeting(greeting);
return ResponseEntity.accepted().body(greetinMsg);
}

 Attributes:

Case 1: How to hide the specific variables from the entity


class.
Using: @JsonIgnore
@JsonProperty: to display only for the response / in json.

ex:
@JsonIgnore

private String emailId

Validations :
application property : server.error.include-binding-errors=always
@NotNull : It doent accept null value but accepts

@NotBlank : doent accept empty value.


@NotEmpty : it doesn’t allow null or emplty value. It
should be applicable only on string, map, collections ,
should not on long , int or any numeric data
@min :
@max :
@JsonProperty:

wrapping entity with DTO (Data Transfer Objects)


@Spring boot devtools – we no need to stop and run the
server always,
How to install the Lombok : goto mvn repository >search lombok,> select present Lombok> download (click on ja to

download )> install/open (give specify location application path) >

Spring JPA Methods

1.Finder methods:

2.JPA methods:

3.Spring JPQL methods: based on query


@Query("SELECT * FROM Student WHERE lastName = :lastname")
List<Student> getStudentsByLastName(String lastname);

Student- class name lastName-field in student class


Spring security
can do by

1.username and password

2.SSO/okta/LDAP

3.App level Authorisation

4.Intra App Authorisation like OAuth

5.Microservice Security (using tokens, JWT)

6.Method level security.

what is authentication, Authorization, principal, Authority, and role?

=> Authentication: who is this user?

1. knowledge based authentication : Password , pin code, Answer to a secret personal question.

it is to implement and easy to use but not fully safe if somebody steal the user name and password they can act like

you.

2.Possession based authentication: phone/text message, key cards and badges, access token device

3.Multi factor authentication:

=> Authorization: Can this user is allowed to do this?

we can also achieve spring security by adding: spring starter security dependency. by default, user name is root

password will be generated by the system.

=>spring security default behavior?

1. Adds mandatory authentication for urls.

2. Adds login form.

3. Handles login errors.


4. Creates a user and sets a default password

=> we can customize username and password

in application properties type : spring.security.user.name=Pavithra

spring.security.user.password=Pavithra@home2

=>How to configure authentication in spring security?

Spring AOP (object oriented programing)

Interview question.

1. What is Spring Boot, and how does it differ from the Spring
framework?
2. What is bean in springboot ?
"bean" refers to an object that is managed by the Spring IoC
(Inversion of Control) container. In simpler terms, a bean is an
instance of a class that Spring manages and provides to other
parts of your application when needed. Beans are fundamental
building blocks in Spring applications, and they play a crucial role
in achieving loose coupling, dependency injection, and modular
design.

3.@component : component is a class managed by spring framwork


4.Dependency injection: Identifying beans , their dependencies and wiring
together (provides ioc – inversion of control)
IOC container: Manages the life cycle of beans and their dependencies.
Types-
1.ApplicationContext
2.BeanFactory
4.AutoWiring : Process of wiring in dependencies for a bean.
What is loose coupling and tight coupling?
5.what are the things available in spring boot 3?
Spring pulsor
Java virtual threads
Ssl bundle support
Rest client
Jdbc client

What is Spring Boot application lifecycle.?

Teaching :
Enhances understanding
Improves communication skills
Builds confidence
Encourages learning
Fosters empathy
How to download docker?
Website : https://www.docker.com/products/docker-desktop/
Install : open->yes->ok-> restart system
Docker is a platform and a set of tools that allows you to develop, deploy, and run
applications in containers. Containers are lightweight, portable, and self-sufficient
environments that contain everything needed to run an application, including the
code, runtime, libraries, and dependencies.

Command prompt
docker –version or docker –v

Important Annotations:
@Transactional :

You might also like