0% found this document useful (0 votes)
3 views

Spring

The document provides an overview of the Spring Framework, highlighting its dominance in the Java ecosystem and key concepts such as Object-Oriented Programming, Dependency Injection, and Inversion of Control. It details the architecture of the Spring Framework, including its core container, data access and integration modules, and various Spring projects. Additionally, it covers Spring beans, their properties, lifecycle, and autowiring modes, along with examples and explanations of important features.

Uploaded by

fecogi8703
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Spring

The document provides an overview of the Spring Framework, highlighting its dominance in the Java ecosystem and key concepts such as Object-Oriented Programming, Dependency Injection, and Inversion of Control. It details the architecture of the Spring Framework, including its core container, data access and integration modules, and various Spring projects. Additionally, it covers Spring beans, their properties, lifecycle, and autowiring modes, along with examples and explanations of important features.

Uploaded by

fecogi8703
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Spring Framework

Lekhraj Varshney & Pranav Gandhi


James Gosling Rod Johnson

Java Spring
Build the apps that make the world run

Spring dominates the Java ecosystem with 60% using it fortheir main
applications
● OOPS Recap
● Introduction to Spring
Framework
Course ● Basics of Spring
● Spring Event Handling
Contents ● Aspect Oriented
Programming
● Spring Boot
Getting The Basics Right

● Object
● Class
● Data Abstraction
● Inheritance
● Data Encapsulation
● Polymorphism
● Dynamic Binding
● Message Passing
Class Vs Object

Class Object
● Blueprint for creating objects ● Instance of a class

● Logical Entity ● Physical entity

● Declared with “class” keyword ● Created using “new” keyword

● Does not get memory when it is ● Gets memory when they are
created created

● Declared once ● Multiple objects are created usinga


class
Data Abstraction

● Programming technique relying on separation of interface and implementation


● Showing only essential information to the user
Example:
abstract class Animal { abstract class Dog extends Animal { public class Main {

void makeSound();public void void makeSound() { public static void main(String[] args) {

eat() { System.out.println("Bark bark"); // create an object of Dog class

System.out.println("I can eat."); }


Dog d1 = new Dog();
} }
d1.makeSound();
}
d1.eat();

}
Data Encapsulation

● Process of binding data members and member functions in a single unit


● Hiding important features of the class not required to be exposed outside ofclass and
exposing only necessary things
Example: class Onboard{
class Student{
public static void main(String[] args)
private int age; // Private is using to hide the data
{
public int getAge() { return age; } // getter
Student s1 = new Student();
public void setAge(int age)
{ s1.setAge(19);

this.age = age; System.out.println("Age: " + s1.getAge());


} // setter }
} }
Homework

● Inheritance
● Polymorphism
● Dynamic Binding
● Message Passing
Dependency Injection vs Inversion of Control

A uses methods from B


Service A Service B
Dependency Injection vs Inversion of Control [Contd]

● Dont call us, we’ll call you


● Dependency Injection is the method of providing the dependencies and
Inversion of Control is the end result of Dependency Injection.
● IoC is a design principle where the control flow of the program is inverted.
Dependency Injection is one of the subtypes of the IOC principle.
● Two types of Spring Dependency Injection are Setter Dependency Injection(SDI)
and Construction Dependency Injection (CDI)
Example of Dependency Injection
Example of Dependency Injection[Contd.]

public String getCompany(){


Engine.java return company;
interface IEngine { }
String EMISSION_NORMS = "BSIV"; public void setCompany(String company){
String importOrigin(); this.company = company;
double cost(); }
} @Override
public String importOrigin(){
return "Japan";
ToyotaEngine.java }
public class ToyotaEngine implements IEngine @Override
{ public double cost(){
String company; return cost;
double cost; }
public double getCost() @Override
{ public String toString(){
return cost; return "This is Engine object
} from: " + company;
}
public void setCost(double cost) }
{
cost = this.cost;
}
Example of Dependency Injection [Contd.]

Tyres.java public void setMessage(String message){


this.message = message;
public class Tyres { }
String name; @Override
String place; public String toString(){
String message; return "This is Tyre object: "+ name +
public String getName(){ " " + place + " " + message;
return name; }
} }
public void setName(String name){
this.name = name;
}
public String getPlace(){
return place;
}
public void setPlace(String place){
this.place = place;
}
public String getMessage(){
return message;
}
Example of Dependency Injection [Contd.]

Vehicle.java public void setEngine(IEngine engine){


public class Vehicle { System.out.println("instantiated via setter");
IEngine engine; this.engine = engine;
Tyres tyre; }
public Tyres getTyre(){ @Override
return tyre; public String toString(){
} return engine + " " + tyre;
public void setTyre(Tyres tyre){ }
System.out.println("tyre instantiated via public static void main(String a[]){
setter"); ApplicationContext rootctx = new
this.tyre = tyre; ClassPathXmlApplicationContext("springContext.x
} ml");
public Vehicle(IEngine engine, Tyres tyre){ // Instantiating the obj1 via Constructor DI
System.out.println("instantiated via Vehicle obj1 = (Vehicle)rootctx
constructor"); .getBean("InjectwithConstructor");
this.engine = engine; // Instantiating the obj1 via Setter DI
this.tyre = tyre; Vehicle obj2 =
} (Vehicle)rootctx.getBean("InjectwithSetter");
System.out.println(obj1);
public Vehicle() {} System.out.println(obj2);
public IEngine getEngine(){ System.out.println(obj1 == obj2);
return engine; }
} }
Example of Dependency Injection [Contd.]

SpringContext.xml
< bean id="tyre1Bean" class="com.tg.Tyres"> <bean id="InjectwithSetter"
<property name="name" value="MRF"></property> class="com.tg.Vehicle">
<property name="place" value="India"></property> <property name="engine" ref="ToyotaBean">
<property name="message" value="Make in India"> </property>
</property> <property name="tyre" ref="tyre1Bean">
</ bean> </property>
<bean id="ToyotaBean" class="com.tg.ToyotaEngine"> </ bean>
<property name="company" value="Toyota"> <bean id="InjectwithConstructor"
</property> class="com.tg.Vehicle">
<property name="cost" value="300000.00"> <constructor - arg name="engine"
</property> ref="ToyotaBean">
</ bean> </ constructor - arg>
< bean id="tyre2Bean" class="com.tg.Tyres"> <constructor - arg name="tyre"
<property name="name" value="TVS"></property> ref="tyre2Bean">
<property name="place" value="India"></property> </ constructor - arg>
<property name="message" value="Make in India"> </ bean>
</property>
</ bean>
Spring framework architecture
Core Container

● The Core module provides the fundamental parts of the framework, including the IoC
and Dependency Injection features.
● The Bean module provides BeanFactory, which is a sophisticated implementation of
the factory pattern.
● The Context module builds on the solid base provided by the Core and Beans modules
and it is a medium to access any objects defined and configured. The
ApplicationContext interface is the focal point of the Context module.
● The SpEL module provides a powerful expression language for querying and
manipulating an object graph at runtime.
Data Access and Integration

● The JDBC module provides a JDBC-abstraction layer that removes the need for
tedious JDBC related coding.
● The ORM module provides integration layers for popular object-relational mapping
APIs, including JPA, JDO, Hibernate, and iBatis.
● The OXM module provides an abstraction layer that supports Object/XML mapping
implementations for JAXB, Castor, XMLBeans, JiBX and XStream.
● The Java Messaging Service JMS module contains features for producing and
consuming messages.
● The Transaction module supports programmatic and declarative transaction
management for classes that implement special interfaces and for all your POJOs.
Web

● The Web module provides basic web-oriented integration features such as multipart
file-upload functionality and the initialization of the IoC container using servlet
listeners and a web-oriented application context.
● The Web-MVC module contains Spring's Model-View-Controller (MVC)
implementation for web applications.
● The Web-Socket module provides support for WebSocket-based, two-way
communication between the client and the server in web applications.
● The Web-Portlet module provides the MVC implementation to be used in a portlet
environment and mirrors the functionality of Web-Servlet module.
Miscellaneous

● The AOP module provides an aspect-oriented programming implementation allowing


you to define method-interceptors and pointcuts to cleanly decouple code that
implements functionality that should be separated.
● The Aspects module provides integration with AspectJ, which is again a powerful and
mature AOP framework.
● The Instrumentation module provides class instrumentation support and class loader
implementations to be used in certain application servers.
● The Messaging module provides support for STOMP as the WebSocket sub-protocol
to use in applications. It also supports an annotation programming model for routing
and processing STOMP messages from WebSocket clients.
● The Test module supports the testing of Spring components with JUnit or TestNG
frameworks.
Spring Projects

● Spring Boot ● Spring Batch


● Spring Data ● Spring AMQP
● Spring Cloud ● Spring Credhub
● Spring Cloud Data Flow ● Spring Flo
● Spring Security ● Spring for Apache Kafka
● Spring for GraphQL ● Spring LDAP
● Spring Session ● Spring Shell
● Spring Integration ● Spring Statemachine
● Spring Hateoas ● Spring Vault
● Spring REST Docs ● Spring Web Flow
● Spring Web Services
Spring IOC Container
Types of IoC Containers
Types of IoC Containers [Contd.]

● Spring BeanFactory Container


This is the simplest container providing the basic support for DI and is defined by the
org.springframework.beans.factory.BeanFactory interface. The BeanFactory & related interfaces, such as
BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purpose of backward
compatibility with a large number of third-party frameworks that integrate with Spring.

● Spring ApplicationContext Container


This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a
properties file and the ability to publish application events to interested event listeners. This container is defined by
the org.springframework.context.ApplicationContext interface.

● The ApplicationContext container includes all functionality of the BeanFactorycontainer, so it is generally


recommended over BeanFactory. BeanFactory can still be used for lightweight applications like mobile devices or
applet-based applications where data volume and speed is significant
Spring beans

● The objects that form the backbone of your application and that are managed bythe
Spring IoC container are called beans.
● A bean is an object that is instantiated, assembled, and otherwise managed by aSpring
IoC container.
● These beans are created with the configuration metadata that you supply to thecontainer.
● Bean definition contains the information called configuration metadata, which isneeded
for the container to know the following −
● How to create a bean
● Bean's lifecycle details
● Bean's dependencies
Spring Beans Properties

● class: This attribute is mandatory and specifies the bean class to be used to create thebean.
● name: This attribute specifies the bean identifier uniquely. In XMLbased configuration
metadata, you use the id and/or name attributes to specify the bean identifier(s).
● scope: This attribute specifies the scope of the objects created from a particular beandefinition
● constructor-arg: This is used to inject the dependencies
● properties: This is used to inject the dependencies
● autowiring mode: This is used to inject the dependencies
● lazy-initialization mode: A lazy-initialized bean tells the IoC container to create a beaninstance
when it is first requested, rather than at the startup
● initialization method: A callback to be called just after all necessary properties on thebean
have been set by the container.
● destruction method: A callback to be used when the container containing the bean is
destroyed.
Spring Beans Scope

● singleton: This scopes the bean definition to a single instance per Spring IoC container(default).
● prototype: This scopes a single bean definition to have any number of object instances.
● request: This scopes a bean definition to an HTTP request. Only valid in the context of aweb-
aware Spring ApplicationContext.
● session: This scopes a bean definition to an HTTP session. Only valid in the context of aweb-
aware Spring ApplicationContext.
● global-session: This scopes a bean definition to a global HTTP session. Only valid in thecontext
of a web-aware Spring ApplicationContext.
Spring Bean Lifecycle
Spring Bean Lifecycle Callback

Initialization callbacks Destruction callbacks


<bean id = "exampleBean" class = <bean id = "exampleBean" class =
"examples.ExampleBean" init-method = "init"/> "examples.ExampleBean" destroy-method =
"destroy"/>
public class ExampleBean {
public void init() { public class ExampleBean {
// do some initialization work public void destroy() {
} // do some destruction work
} }
}
Spring environment setup

● Setup JDK
● Setup IDE (Intellij, Java)
● Setup spring libraries using maven/gradle or manually downloading the libraries
Creating bean using factory bean

Bean to create: Factory Instance:


public class Foo {} public class InstanceFooFactory {
public Foo createInstance() {
return new Foo();
}
}

Spring Xml: Creating Foo Bean:


<beans ...> @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/factorymethod/instance-config.xml
<bean id="instanceFooFactory" ")
public class InstanceFooFactoryIntegrationTest {
class="com.baeldung.factorymethod.Instan
ceFooFactory" /> @Autowired
private Foo foo;
<bean id="foo"
factory-bean="instanceFooFactory" @Test
factory-method="createInstance" /> public void
givenValidInstanceFactoryConfig_whenCreateFooInstance_the
</beans> nInstanceIsNotNull() {
assertNotNull(foo);
}
Spring bean autowire and its type

Spring provides a way to automatically detect the relationships between various beans. This can be done by
declaring all the bean dependencies in Spring configuration file. So, Spring is able to utilize the
BeanFactory to know the dependencies across all the used beans.

Spring supports the following autowiring modes:

● no: It’s the default autowiring mode. It means no autowiring.


● <bean id="car" class="com.example.Car">
● <property name="engine" ref="engineBean"/>
● </bean>
● byName: Injects the object dependency according to name of the bean. In such a case, theproperty
and bean name should be the same. It internally calls the setter method.
● <bean id="car" class="com.example.Car" autowire="byName"/>

● byType: The byType mode injects the object dependency according to type. So it can have adifferent
property and bean name. It internally calls the setter method.
<bean id="car" class="com.example.Car" autowire="byType"/>
● constructor: Spring matches constructor parameters with beans by type.
<bean id="car" class="com.example.Car" autowire="constructor"/>
● autodetect: Deprecated from version 3.0+

● Spring first attempts constructor autowiring, then byType.

● Annotation-based Autowiring:
● @Autowired -- Automatically injects a bean by type

@Component
public class Car
{
@Autowired
private Engine engine;
}
Spring bean autowire and its types[Contd.]

Example:

<bean id="department" class="com.autowiringdemo.Department">


<property name="deptName" value="Information Technology" />
</bean>
<bean id="employee" class="com.autowiringdemo.Employee"></bean>
<bean id="employee" class="com.autowiringdemo.Employee" autowire="byName"></bean>
<bean id="employee" class="com.autowiringdemo.Employee" autowire="byType"></bean>
<bean id="employee" class="com.autowiringdemo.Employee" autowire="constructor"></bean>

public class Department {


private String deptName;
public String getDeptName() {
return deptName;
}
public void setDeptName(String
deptName) {
this.deptName = deptName;
}
}
Spring bean autowire and its types[Contd.]

Example:

public class Employee @SpringBootApplication


{private int eid; public class AutowiringdemoApplication {
private String ename; public static void main(String[] args) {
private Department department; SpringApplication.run(
//getters and setters AutowiringdemoApplication.class, args);
public void showEployeeDetails(){ ApplicationContext context = new
System.out.println("Employee Id: "+eid); ClassPathXmlApplicationContext("applicationContex
System.out.println("Employee Name: t.xml");
"+ename); System.out.println("Department: Employee emp = context.getBean("employee",
"+ Employee.class);
department.getDeptName()); emp.setEid(101);
} emp.setEname("Spring Framework Guru");
} emp.showEployeeDetails();
}
}
Best practices of spring framework

https://examples.javacodegeeks.com/enterprise-java/spring/20-spring-framework-best-practices/
Spring java configuration vs xml

● XML configurations can take a lot of work when there are a lot of beans, while annotations
minimize the XML configurations.
● Annotation injection is performed before XML injection. Thus, XML configurations will
override that of the annotations.
Spring Event Handling

● Traditional methods vs events


● Give developers a way for different components to communicate and have more flexibilitywith each
other than the traditional method calls
● Leads to more flexible and loosely coupled architectural design
● Provides published subscribe capability which means subscribers can be added orremoved at any
point in time
● Spring Built in events:
- ContextRefreshedEvent: Published when the ApplicationContext is either initialized or
refreshed
- ContextStartedEvent: Published when the ApplicationContext is started
- ContextStoppedEvent: Published when the ApplicationContext is stopped
- ContextClosedEvent: Published when the ApplicationContext is closed
- RequestHandledEvent: Web-specific event telling all beans that an HTTP request has beenserviced.
Spring Event Handling - Example

public class CustomEvent


{
private String message;
public CustomEvent(String message)
{
this.message = message;
}
public String getMessage()
{
return message;
}
}
Spring Custom Event

Must extend the ApplicationEvent


public class CustomEvent extends ApplicationEvent{ public class CustomEventHandler implements
public CustomEvent(Object source) { ApplicationListener<CustomEvent> {
super(source); public void onApplicationEvent(CustomEvent event) {
} System.out.println(event.toString());
public String toString(){ }
return "My Custom Event";
} public class MainApp {
} public static void main(String[] args) {
ConfigurableApplicationContext context =
public class CustomEventPublisher implements new ClassPathXmlApplicationContext("Beans.xml");
ApplicationEventPublisherAware { CustomEventPublisher cvp =
private ApplicationEventPublisher publisher; (CustomEventPublisher) context.getBean("customEventPublisher");
public void setApplicationEventPublisher cvp.publish();
(ApplicationEventPublisher publisher) { cvp.publish();
this.publisher = publisher; }
} }
public void publish() {
CustomEvent ce = new CustomEvent(this); <bean id = "customEventHandler" class =
publisher.publishEvent(ce); "com.tutorialspoint.CustomEventHandler"/>
} <bean id = "customEventPublisher" class =
}
"com.tutorialspoint.CustomEventPublisher"/>
Aspect Oriented Programming

● Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing


another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in
AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns such as transaction
management that cut across multiple types and objects.
● Dependency Injection helps you decouple your application objects from each other and AOP helps you
decouple cross-cutting concerns from the objects that they affect.
● These cross-cutting concerns are conceptually separate from the application's business logic. There are
various common good examples of aspects like logging, auditing, declarative transactions, security,
caching, and exception handling without polluting the core business logic . etc
Aspect Oriented Programming - Terminologies

● Aspect: Class that implements the JEE application concerns


which cut through multiple classes. Configured through Spring
XML configuration or using @Aspect annotation.
Ex: Logging or transaction management.
● Join point: Point in application where you can plug-in AOP
aspect.
● Advice: Actual action to be taken before/after the method
execution.
● Point Cut: Set of one or more join points where an advice
should be executed.
● Proxy: An object created after applying advice to the target
object
● Target Object: The object being advised by one or more
aspects

Weaving: Process of linking aspects with other application
types or objects to create an advised object
Aspect Oriented Programming - Types of Advice

● before: Run advice before the a method execution.


● after: Run advice after the method execution, regardless of its outcome.
● after-returning: Run advice after the a method execution only if method completessuccessfully.
● after-throwing: Run advice after the a method execution only if method exits by throwing an
exception.
● around: Run advice before and after the advised method is invoked.

● Public class PaymentService


● {
//Without modification insert code using AOP—add external services here
● Public void payment()
● {
------------------
------------------
● }
● }
Aspect Oriented Programming - Custom Aspects Implementation

Spring supports the @AspectJ annotation style approach and the schema-based approach toimplement
custom aspects.

● XML Schema based: Aspects are implemented using the regular classes along with XMLbased
configuration.
● @AspectJ based: @AspectJ refers to a style of declaring aspects as regular Javaclasses
annotated with Java 5 annotations.
Aspect Oriented Programming - Example

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop
https://www.digitalocean.com/community/tutorials/spring-aop-example-tutorial-aspect-advice-pointcut-joinp oint-annotations

You might also like