0% found this document useful (0 votes)
8 views10 pages

Spring Introduction

The document provides an overview of Spring Boot and microservices, detailing concepts such as programming languages, frameworks, and the Spring framework's modules and advantages. It explains the structure of a Spring application, dependency injection methods, and the principles of RESTful web services, including HTTP methods and status codes. Additionally, it highlights security best practices and the benefits of using REST with Spring Boot for building scalable web APIs.

Uploaded by

roulrajendra400
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views10 pages

Spring Introduction

The document provides an overview of Spring Boot and microservices, detailing concepts such as programming languages, frameworks, and the Spring framework's modules and advantages. It explains the structure of a Spring application, dependency injection methods, and the principles of RESTful web services, including HTTP methods and status codes. Additionally, it highlights security best practices and the benefits of using REST with Spring Boot for building scalable web APIs.

Uploaded by

roulrajendra400
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

Springboot and Microservices

=============================

Language
========
1.A language is a set of words.
[Link] purpose of language is to communicate 1 person with another person.

Ex
--
Telugu
Hindi
Tamil
English.......

programming Language
=====================
1.A programming language is a set of instructions.
[Link] purpose of programming language is to communicate 1 person with 1 machine.

Ex
--
c
cpp
java
python....

Framework
==========
[Link] is a semi developed software.
[Link] purpose of framework is to provide common logics to application development.

Ex
--
Hibernate
structs
spring......

Hibernate
---
[Link] is a ORM framework.
[Link] is used to develop persistence layer(Database layer)

structs
---
[Link] is a webframework.
[Link] is used to develop weblayer.

spring Framework
---
[Link] is a application development framework.
[Link] is used to develop end to end application.
[Link] purpose of spring framework is to develop following applications.
[Link] applications.
[Link] applications.
[Link] applications.
[Link] contains following [Link] are
[Link] core
[Link] jdbc
[Link] Aop
[Link] orm
[Link] data jpa
[Link] web mvc
[Link] security
[Link] cloud
[Link] batch........

Advantages
===========
[Link] is a open source framework.
[Link] is a light weight framework.
[Link] is versatile framework.
[Link] is a non invasive framework.
[Link] works based on pojo and poji model
pojo :plain old java object
poji :plain old java interface

spring can be integrated with any other java framework


spring framework did not force to implements,extends interface or class.

Note:If we develop an application with spring developer want to develop business


logics.
If we develop an application without spring developer want to develop both
business logics and common logics.
===================================================================================
=======================================
[Link] core
==============
[Link] core is base module in spring framework.
[Link] the other modules of spring are developed on top spring core only.
[Link] core providing fundamenetals concepts of spring framework.
IOC Container and Dependency Injection

[Link] core is used to create objects and inject objects among all classes.

Project structure
=================

projectName
src/main/java
src/main/resources

src/test/java
src/test/resources

JRE
src
Target
[Link]

src/main/java
---
It is used to store java related files
src/main/resources
---
It is used to store project related files

src/test/java
---
It is used to store unit testing related files

src/test/resources
---
It is used to store test project related files

[Link]
---
It is used to store dependencies.

[Link]
========
package [Link];

public class Car {

public Car()
{
[Link]("Car constructor");
}

[Link]
=========
package [Link];

public class Main {

public static void main(String[] args) {

Car c1=new Car();


}

[Link] a first spring application.

Required Files
==============
[Link](spring context dependency)
[Link]
[Link]
[Link]

[Link]
=======
[Link] is used to used to add dependencies required for application.
[Link]
==========
[Link] is used to create spring bean definitions and assign values.

IOC Container
=============
[Link] stands for Inversion of Controller.
[Link] purpose of IOC Container is to create objects.
[Link] want to start IOC Container in method class by using below

ApplicationContext context=new ClassPathXmlApplicationContext("[Link]");

[Link]
=======
<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>
<groupId>[Link]</groupId>
<artifactId>SpringFirstApp</artifactId>
<version>0.0.1-SNAPSHOT</version>

<dependencies>

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.20</version>
</dependency>

</dependencies>
</project>

[Link]
========
package [Link];

public class Car {

public Car()
{
[Link]("car constructor Bye");
}
}

[Link]
===========
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<bean id="car1" class="[Link]">
</bean>

</beans>

[Link]
==========
package [Link];

import [Link];
import [Link];

public class Main1 {

public static void main(String[] args) {

ApplicationContext context=new
ClassPathXmlApplicationContext("[Link]");

Car c=[Link]("car1",[Link]);
}

Dependency Injection:-

Dependency Injection (DI) is a design pattern in which objects receive their


dependencies from an external source rather than creating them internally. It
promotes loose coupling, easier testing, and better code maintainability. In
Spring, DI is achieved mainly through Constructor Injection or Setter Injection.

Types of Spring Dependency Injection


There are two primary types of Spring Dependency Injection:

1. Setter Dependency Injection (SDI)

2. Constructor Dependency Injection (CDI)

3. Field Injection

1. Setter Dependency Injection (SDI)

Setter Injection involves providing the dependency via a setter method after the
object is created. This approach is more flexible than constructor injection
because it allows dependencies to be set or changed after object creation.

2. Constructor Dependency Injection (CDI)

With Constructor Injection, dependencies are provided to a class through its


constructor when the object is created. This is the most common form of DI because
it makes dependencies clear, mandatory, and immutable after the object is
constructed.

[Link] Injection

Autowiring :-

Autowiring in the Spring framework can inject dependencies automatically. The


Spring container detects those dependencies specified in the configuration file and
the relationship between the beans. This is referred to as Autowiring in Spring. To
enable Autowiring in the Spring application we should use @Autowired annotation.
Autowiring in Spring internally uses constructor injection. An autowired
application requires fewer lines of code comparatively but at the same time, it
provides very little flexibility to the programmer.

This mode tells the framework that autowiring is not supposed to be done. It is the
default mode used by Spring.

byName

It uses the name of the bean for injecting dependencies.

byType

It injects the dependency according to the type of bean.

Constructor

It injects the required dependencies by invoking the constructor.

Autodetect

The autodetect mode uses two other modes for autowiring - constructor and byType.

1. No
This mode tells the framework that autowiring is not supposed to be done. It is the
default mode used by Spring.

<bean id="state" class="[Link]">


<property name="name" value="UP" />
</bean>
<bean id="city" class="[Link]"></bean>

2. byName
It uses the name of the bean for injecting dependencies. However, it requires that
the name of the property and bean must be the same. It invokes the setter method
internally for autowiring.

<bean id="state" class="[Link]">


<property name="name" value="UP" />
</bean>
<bean id="city" class="[Link]" autowire="byName"></bean>

3. byType
It injects the dependency according to the type of the bean. It looks up in the
configuration file for the class type of the property. If it finds a bean that
matches, it injects the property. If not, the program throws an error. The names of
the property and bean can be different in this case. It invokes the setter method
internally for autowiring.

<bean id="state" class="[Link]">


<property name="name" value="UP" />
</bean>
<bean id="city" class="[Link]" autowire="byType"></bean>

4. constructor
It injects the required dependencies by invoking the constructor. It works similar
to the “byType” mode but it looks for the class type of the constructor arguments.
If none or more than one bean are detected, then it throws an error, otherwise, it
autowires the “byType” on all constructor arguments.

<bean id="state" class="[Link]">


<property name="name" value="UP" />
</bean>
<bean id="city" class="[Link]" autowire="constructor"></bean>

5. autodetect
The autodetect mode uses two other modes for autowiring - constructor and byType.
It first tries to autowire via the constructor mode and if it fails, it uses the
byType mode for autowiring. It works in Spring 2.0 and 2.5 but is deprecated from
Spring 3.0 onwards.

<bean id="state" class="[Link]">


<property name="name" value="UP" />
</bean>
<bean id="city" class="[Link]" autowire="autodetect"></bean>

Advantage of Autowiring: It requires less code because we don't need to write the
code to inject the dependency explicitly.
Disadvantage of Autowiring: No control of the programmer and It can't be used for
primitive and string values.

Spring AOP (Aspect-Oriented Programming) is a programming technique in the Spring


Framework that helps separate cross-cutting concerns (like logging, security,
transactions) from the main business logic. Instead of adding this logic inside
every class, AOP allows you to write it once and apply it wherever needed.

In Spring, AOP works using proxies and you can define behaviors using annotations
like @Aspect, @Before, @After and @Around. This keeps your code clean, modular and
easier to maintain by focusing only on the core business functionality while AOP
handles the repetitive system-level tasks behind the scenes.

Understanding AOP Concepts


1. Aspect: An Aspect is a modular unit of cross-cutting concerns. For example, a
logging aspect can be applied across various methods in different classes.

2. Advice: This is the action taken by an aspect at a particular join point. There
are five types of advice:

Before: Executed before the method call.

After: Executed after the method call, regardless of its outcome.

AfterReturning: Executed after the method returns a result, but not if an exception
occurs.

Around: Surrounds the method execution, allowing you to control the method
execution and its result.

AfterThrowing: Executed if the method throws an exception.

Advice-in-AOP
Advice in AOP
3. Join Point: A specific point in the execution of a program, such as method
execution or exception handling, where an aspect can be applied.

4. Pointcut: A Pointcut is a predicate that defines where advice should be applied.


It matches join points using expressions.

5. Weaving: This is the process of linking aspects with the target object. Spring
AOP only supports runtime weaving using proxy-based mechanisms (JDK dynamic proxies
for interfaces and CGLIB for concrete classes). It does not modify bytecode like
AspectJ.

Dominant AOP Frameworks


Spring-AOP
AOP Frameworks
AspectJ: A powerful and mature AOP framework that supports compile-time and load-
time weaving. It offers full AOP support with its own syntax and tools.
JBoss AOP: Part of the JBoss application server, offering integration with Java EE
applications.
Spring AOP: A simpler, proxy-based framework that integrates with the Spring
Framework, using XML configurations or annotations to define aspects and pointcuts.
Example

RESTful Web Services provide a standard approach to building scalable, stateless


web APIs using HTTP. REST (REpresentational State Transfer) was introduced by Roy
Thomas Fielding as an architectural style to optimize the use of HTTP. Unlike SOAP,
REST does not rely on a strict messaging protocol, it can use multiple formats such
as JSON or XML, with JSON being the most widely adopted.

Key Concepts
Resource: Any object, entity, or service that can be accessed via a URI.
Stateless Communication: Each HTTP request contains all the information needed to
process it.
Representations: Resources can be represented in different formats (JSON, XML,
HTML, PDF, etc.).
HTTP Verbs: REST leverages standard HTTP methods for CRUD operations.
HTTP Methods
The main methods of HTTP we build web services for are:

GET: Reads existing data.


PUT: Updates existing data.
POST: Creates new data.
DELETE: Deletes the data.

HTTP Status Codes


200: Success
201: Created
401: Unauthorized
404: Resource Not Found
500: Server Error

1. GET – Read Resource


Retrieves data without a request body.
Can fetch a specific resource using an ID or a collection without parameters.
Spring Boot Example:

@GetMapping("/user/{userId}")
public ResponseEntity<UserEntity> getUser(@PathVariable int userId) {
UserEntity user = [Link](userId);
return [Link](user);
}

2. POST – Create Resource


Creates a new resource using a request body.
Spring Boot Example:

@PostMapping("/user")
public ResponseEntity<String> addUser(@RequestBody UserEntity user) {
[Link](user);
return [Link]([Link]).body("User created
successfully");
}

3. PUT – Update Resource


Updates an existing resource identified by ID.
Spring Boot Example:

@PutMapping("/user/{userId}")
public ResponseEntity<String> updateUser(@PathVariable int userId, @RequestBody
UserEntity user) {
[Link](user);
return [Link]("User updated successfully");
}

4. DELETE – Remove Resource


Deletes a single or multiple resources based on parameters.
Spring Boot Example:

@DeleteMapping("/user/{userId}")
public ResponseEntity<String> deleteUser(@PathVariable int userId) {
[Link](userId);
return [Link]("User deleted successfully");
}

REST APIs rely on these codes to communicate the result of client requests.

Principles of RESTful Web Services


Resource Identification via URI: Every resource has a unique URI.
Uniform Interface: CRUD operations use standard HTTP methods: GET, POST, PUT,
DELETE.
Self-Descriptive Messages: The request and response contain all necessary
information.
Stateless Interactions: Each request is independent; no session data is stored on
the server.
Cacheable: Responses can be cached when appropriate to improve performance.
Security Best Practices for REST APIs
Authentication and Authorization: Use JWT or OAuth 2.0.
Input Validation: Sanitize requests to prevent SQL injection and XSS attacks.
HTTPS Enforcement: Ensure all communications are encrypted.
Rate Limiting: Protect against abuse by limiting request rates.
Advantages of RESTful Web Services
Simple and Lightweight: Easier to develop and consume compared to SOAP.
Client-Server Decoupling: Enables independent development of client and server.
Scalable: Stateless communication supports horizontal scaling.
Layered System Architecture: Applications can be divided into layers, enhancing
modularity and maintainability.
Cacheable: Responses can be cached to improve performance and reduce bandwidth.
Uses of REST with Spring Boot
Spring Boot makes building RESTful APIs fast and efficient by:

Simplifying configuration and setup.


Providing out-of-the-box support for JSON and XML serialization.
Allowing integration with databases, messaging systems, and external APIs.
Supporting advanced features like validation, exception handling, and security.

===================================================================================
===================================
===================================================================================
===================================

You might also like