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

Spring Boot for Developers

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Topics covered

  • Spring Boot,
  • RESTful Services,
  • SSL Support,
  • Microservices,
  • DTO,
  • Java Virtual Threads,
  • Entity Class,
  • Docker,
  • Dependency Injection,
  • JDBC Client
0% found this document useful (0 votes)
532 views19 pages

Spring Boot for Developers

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Topics covered

  • Spring Boot,
  • RESTful Services,
  • SSL Support,
  • Microservices,
  • DTO,
  • Java Virtual Threads,
  • Entity Class,
  • Docker,
  • Dependency Injection,
  • JDBC Client
  • Introduction to Spring Boot: Provides an introduction to Spring Boot, touching on its open-source nature and initial configuration steps.
  • Spring Boot Application Setup: Covers detailed steps to download, initialize, and configure a Spring Boot application, including dependency injection and application properties.
  • Understanding CRUD Operations: Details the CRUD operations essential to database manipulation within a Spring Boot application.
  • Application Properties and Postman: Discusses the application properties configuration and introduces Postman as a tool for testing APIs.
  • Spring Framework Modules: Overview of the different modules within the Spring Framework and their interactions in application development.
  • Spring Projects Overview: An overview of various Spring projects, emphasizing REST API development and microservices with Spring Boot.
  • Developing APIs with Spring Boot: Guides the reader through the steps required to create APIs using Spring Boot, focusing on repositories and services.
  • Swagger Integration and Deployment: Explores using Swagger for API documentation and details steps for deploying a project on Tomcat server.
  • Spring Security: Discusses security measures in Spring, including authentication, authorization, and various security configurations.
  • Interview Preparations and Concepts: Provides commonly asked Spring Boot interview questions and explores important concepts for understanding the framework.
  • Docker Usage and Annotations: Offers instructions for installing Docker and important annotations used in Spring Boot.

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 :

Common questions

Powered by AI

Lombok is a Java library that helps to reduce boilerplate code in Spring Boot projects by automatically generating commonly used methods such as getters, setters, equals, hashCode, and toString methods. In a Spring Boot project, it simplifies the code by eliminating repetitive code, thus improving readability and maintainability . Specifically, it enhances code quality by reducing human error involved in writing standard methods and decreases the time needed for code maintenance. Lombok also helps developers to focus more on business logic rather than on boilerplate code, contributing to cleaner and more efficient codebase .

CRUD operations in a Spring Boot application can be handled using HTTP methods mapped to specific Repository methods. For 'Create', you use the POST method to add new records, typically creating an endpoint that processes user data from the request body and saves it to the database . For 'Read', GET methods retrieve records, often fetching data by ID passed as a path variable . 'Update' uses PUT or PATCH methods to modify records, processing the updated data and applying changes to the database . Lastly, 'Delete' operations are usually performed with DELETE methods to remove records by calling the appropriate repository delete method . Utilizing these methods effectively involves designing clear API endpoints, managing exceptions, and ensuring data validation.

Spring Boot enables autoscan of components using the @SpringBootApplication annotation. This annotation is a convenience annotation that is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan together . @ComponentScan specifies the base packages to scan for Spring components, enabling automatic detection of classes annotated with @Component, @Service, @Repository, etc., within the specified packages. @EnableAutoConfiguration attempts to automatically configure your Spring application based on the jar dependencies present. This setup reduces the need for explicit configuration and ensures that application components are properly detected and registered in the application context.

The @GetMapping annotation in Spring Boot is used to map HTTP GET requests onto specific handler methods in a controller, facilitating basic read operations in a RESTful service . It simplifies method declaration by reducing boilerplate code associated with specifying HTTP methods. The @PathVariable annotation allows for mapping of URLs with placeholders to method parameters, enabling dynamic retrieval of resource identifiers directly from the URL path . This approach enhances the clarity and REST-compliance of URIs by embedding identifiable data within URL segments, thus promoting cleaner and more intuitive API designs. Their combined usage in service endpoints allows precise and comprehensive request handling with minimal configuration, contributing to efficient service design and execution in Spring-based applications.

Spring Boot handles exception management primarily through the use of @ControllerAdvice and @ExceptionHandler annotations which allow central management of exceptions across the application . The @ControllerAdvice annotation is used to define a global exception handler class that handles exceptions thrown by various components. Within this class, you specify methods with @ExceptionHandler that are tailored to handle specific exceptions. Additionally, @ResponseStatus can be used on custom exception classes to define HTTP response codes directly, facilitating consistent error responses. This setup provides a centralized, consistent, and declarative approach to handle application-wide exceptions, ensuring that all exceptions are processed in a predictable manner and that clients receive meaningful error responses .

To optimize Spring Boot for deployment on a Tomcat server, the application should be packaged as a WAR (Web Application Archive) file instead of the default JAR . This involves modifying the Spring Boot project setup, ensuring it extends SpringBootServletInitializer for servlet container support. In addition, you need to adjust the packaging setting in the pom.xml to WAR and configure the Maven build to include any necessary dependencies that won't be provided by the server. Configuration of server-related properties, such as port, context path, and resource handling in application.properties, also play a crucial role . It is important to ensure compatibility between the application and the Tomcat server version, optimizing performance through connection pooling and session management settings. Proper logging and monitoring configurations should be prioritized to diagnose deployment-related issues efficiently.

Implementing a service layer in a large-scale Spring Boot application involves creating interfaces and classes that contain business logic, typically separating it from controllers and repositories. The service layer acts as an intermediary between the controller (presentation layer) and the repository (data access layer), ensuring that business rules are applied consistently across different application modules . The primary benefit is that it promotes code reusability, maintainability, and scalability, enabling team collaboration by providing clear boundaries and reducing coupling between components. It also improves testability of business logic and facilitates easier code updates and debugging since the logic is isolated in a single layer . In terms of architectural organization, it provides a clean separation of concerns, resulting in a robust and flexible application structure.

Authentication and Authorization are two separate concepts in Spring Security with distinct roles. Authentication is the process of verifying the identity of a user, determining 'who' the user is. It can be performed using knowledge-based methods (like passwords), possession-based methods (like tokens), and multi-factor authentication to enhance security . Authorization, on the other hand, determines the access level and permissions of the authenticated user, answering the question 'what can the user do?' This is usually handled through roles and permissions configured in the security settings. Implementation in Spring Security involves configuring an AuthenticationManager for user validation and AccessDecisionManager to check user roles against secured resources, typically via annotations like @PreAuthorize in controller methods or through XML/Java configuration . These concepts provide a comprehensive security framework in Spring applications, ensuring both user identity verification and controlled access to application resources.

A JAR (Java ARchive) file is a package file format used to aggregate many Java class files, metadata, and resources such as images and text into one file for distribution . In Spring Boot, JAR files are crucial as they serve as the deployment unit of the application. Specifically, they encapsulate the entire application along with its dependencies into a single runnable file, which simplifies distribution and execution. This portability ensures that the application can be easily deployed across different environments, enhancing the deployment process by providing a self-contained package that is independent of the development environment .

Different architectural layers in a Spring Boot API, such as the Controller, Service, Repository, and Data layers, are designed to separate concerns, enhancing code organization and maintainability . The Controller layer handles HTTP requests and responses, directing them to the appropriate service methods. The Service layer encapsulates business logic and transaction management, offering a central point for enforcing business rules. The Repository layer abstracts data access, often using JPA to communicate with databases, while the Data layer may involve data transformation and validation . These layers promote loose coupling, allowing independent development and testing of components, facilitating parallel development efforts. They also support scalability, enabling the application to respond to changes or increased load efficiently. By maintaining distinct boundaries between responsibilities, architectural layers facilitate easier debugging, testing, and updating of the application, contributing to a robust, maintainable, and scalable system.

You might also like