SlideShare ist ein Scribd-Unternehmen logo
1 von 43
Spring Framework

Prepared & Presented by

Arjun
1
Know your trainer
Name: Arjun
Phone : +91 9691053479
Email: thakurarjun247@gmail.com

 Freelance corporate trainer.
 More than 2 years of strong hands-on experience in top MNCs in Java
and related technologies.
 More than 2 years of experience as a Java trainer.
Clients / Previous Employers:

2
Agenda

Topics to be covered are:






Introduction to Spring framework
Benefits of Spring framework
Spring framework architecture
Inversion of Control (IoC)
Dependency Injection (DI)

3
Spring Framework

 Light-weight comprehensive framework for building Java SE and
Java EE applications
 Created by Rod Johnson
 JavaBeans-based configuration management, applying Inversionof-Control principles, specifically using the Dependency Injection
technique
• Reduce dependencies of components on specific
implmentation of other components.
• A core bean factory, which is usable globally
 Generic abstraction layer for database transaction management

4
Key Features

 Built-in generic strategies for JTA and a single JDBC DataSource
 This removes the dependency on a Java EE environment for
transaction support.
 Integration with persistence frameworks Hibernate, JDO and
iBATIS.
 MVC web application framework, built on core Spring functionality,
 supporting many technologies for generating views, including JSP.
 Extensive aspect-oriented programming (AOP) framework to
provide
 services such as transaction management.
 As with the Inversion-of-Control parts of the system, this aims to
improve the modularity of systems created using the framework.

5
Using Spring

 Wiring of components through Dependency Injection
 Promotes de-coupling among the parts that make the
application
 Test-Driven Development (TDD)
 POJO classes can be tested without being tied up with
the framework
 Declarative programming through AOP
 Easily configured aspects, esp. transaction support
 Integration with other technologies
 EJB for J2EE
 Hibernate, iBatis, JDBC (for data access)
 Velocity (for presentation)
 Struts and WebWork (For web)

6
Spring Framework

7
Core Package

 The fundamental part which provides the IoC and Dependency
Injection features
 BeanFactory, provides a sophisticated implementation of the
factory pattern
 Removes the need for programmatic singletons
 Decouple the configuration and specification of dependencies in
program logic.

8
Context Package

 Provides a way to access objects in a framework-style
 Inherits its features from the beans package and adds support for
• internationalization (I18N)
• event-propagation
• resource-loading
• transparent creation of contexts by

9
DAO Package

 Provides a JDBC-abstraction layer that removes the need to do
tedious
 JDBC coding and parsing of database-vendor specific error codes
 Programmatic as well as declarative transaction management for
• classes implementing special interfaces
• POJOs

10
ORM Package

 The ORM package provides integration layers for popular objectrelational mapping APIs, including JPA, JDO, Hibernate, and iBatis.
 Using the ORM package you can use all those O/R-mappers in
combination with all the other features Spring offers, such as the
simple declarative transaction management feature mentioned
previously

11
AOP Package

 Spring's AOP package provides an AOP Alliance-compliant aspectoriented programming implementation
• method-interceptors and pointcuts to cleanly decouple code
implementing functionality that should logically speaking be
separated
 Using source-level metadata functionality you can also incorporate all
kinds of behavioral information into your code

12
MVC Package

 Web package provides features, such as
• multipart file-upload functionality,
• the initialization of the IoC container using servlet listeners
• A web-oriented application context.
• Can be used together with WebWork or Struts,
 Spring's MVC package provides a Model-View-Controller (MVC)
 implementation for web applications
 Provides a clean separation between domain model code and web
forms, and allows all the other features of the Spring Framework.

13
IoC Container







Introduction
Basic Containers and Beans
Dependencies
The Application Context
Developing a Spring Application

14
Inversion of Control

 The Spring IoC container makes use of Java POJO classes and
configuration metadata.
 It produces a fully configured and executable system or application.

15
Introduction to IoC

 Traditional software is developed with the application code “in
control”
• The application defines the “main”function/method/entry point
• Calls the application’s components to perform processing
 Frameworks invert this relationship and call the application code
• “Don’t call us we’ll call you”
• Framework provides the “main”function/method/entry point
• Application code fits into the framework and is called when the
framework decides.
 A particular variant of IoC is “dependency injection”

16
Dependency Injection

 Most frameworks use the “Service Lookup” approach to allow
application code to find its dependencies.
• e.g. J2EE code looks up resources via JNDI
• CORBA applications find services via a Naming Service
• The lookup mechanism is hard coded into the application code
 Dependency Injection frameworks supply the resources that a
component needs when initialising it
• Component declares resources required (usually as interface
types)
• Framework configuration defines concrete instances to use
• Framework passes component the concrete resources at load
time
 “IoC containers” are “Dependency Injection” containers

17
Service Lookup vs. Dependency Injection

18
IoC Container

 The org.springframework.beans and org.springframework.context
packages provide the basis for the Spring Framework's IoC container.
 BeanFactory interface
provides an advanced configuration mechanism capable of managing
 objects of any nature.
 ApplicationContext interface , a sub interface of BeanFactory is used
for
• Easier integration with Spring's AOP features,
• Message resource handling (in internationalization),
• Event propagation
• Specific contexts such as the WebApplicationContext

19
Container and Beans

 A bean is simply an object that is instantiated, assembled and
otherwise managed by a Spring IoC container
 The beans, and the dependencies between them, are reflected in
the configuration metadata used by a container.
 org.springframework.beans.factory.BeanFactory is the representation
of the Spring IoC container, it’s responsible for:
• containing and managing beans,
• instantiating or sourcing application objects
• configuring such objects
• assembling the dependencies between objects.

20
The Container

 There are a number of implementations of the BeanFactory interface
 The most commonly used BeanFactory implementation is the
XmlBeanFactory class.
 The XmlBeanFactory takes the XML configuration metadata and uses
it to create a fully configured system or application.

21
Configuration Meta Data

 The meta-data informs the Spring container as to how to “instantiate,
configure, and assemble *the objects in your application+”.
 XML-based metadata is the most commonly used form of
configuration metadata.
 Configuration consists of at least one bean definition that the
container must manage, but could be more than one bean definition.
 When using XML-based configuration metadata, these beans are
configured as <bean/> elements inside a top-level <beans/> element.

22
Simple XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans2.5.xsd">
<bean id="..." class="...">
<!--collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!--collaborators and configuration for this bean go here -->
</bean>
<!--more bean definitions go here -->
</beans>

23
Instantiating a Container

ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] {"services.xml", "daos.xml"});

// an ApplicationContext is also a BeanFactory (via inheritance)
BeanFactory factory = context;

24
The Bean

 The container manages the beans , and they are are created using
the configuration metadata.
 Bean definitions are represented as BeanDefinition objects, which
contain the following metadata:
 package-qualified class name: typically this is the actual
implementation class of the bean being defined.
 bean behavioral configuration elements,
• which state how the bean should behave in the container (scope,
lifecycle callbacks etc.,).
 references to other beans
• which are needed for the bean to do its work; these references
are also called collaborators or dependencies.
 other configuration settings
• An example would be the number of connections to use in a
bean that manages a connection pool, or the size limit of the
pool.
25
Benefits of Dependency Injection

 Flexible
• Avoid adding lookup code in business logic

 Testable
• No need to depend on external resources or containers for
testing
 Maintainable
• Promotes a consistent approach across all applications and
teams
• Allows reuse in different application environments by changing
configuration files instead of code

26
Dependency Injection






BeanFactory interface
XmlBeanFactory implementation
Bean configuration file
Constructor dependency Injection
• Dependencies are provided through the constructors of the
component
 Setter dependency injection
• Dependencies are provided through the JavaBeanstyle setter
methods of the component
• More popular than Constructor dependency injection
 Beans
 Injection Parameters

27
BeanFactory Class

 BeanFactory object is responsible for managing beans and their
dependencies
 Your application interacts with Spring's DI container through
BeanFactory interface
• BeanFactory object has to be created by the application typically
XmlBeanFactory
• BeanFactory object, when it gets created, read bean
configuration file and performs the wiring
• Once created, the application can access the beans via
BeanFactory interface
 XmlBeanFactory
• Convenience extension of DefaultListableBeanFactory that reads
bean definitions from an XML document

28
Beans

 The term “bean” is used to refer any component managed by the
BeanFactory
 The “beans” are in the form of JavaBeans (in most cases)
• no arg constructor
• getter and setter methods for the properties
 Beans are singletons by default
 Properties
• the beans may be simple values or references to other beans

29
The Bean – A Java Class

public class Example {
private int empid;
private String empname;
public int getEmpid() {
return empid;
}
public void setEmpid(int empid) {
this.empid = empid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public Example() {super();}} // no arg constructor
30
Injecting Simple Values–XML File

 Each bean is defined using <bean> tag under the root of the <beans>
tag
 The id attribute is used to give the bean its default name
 The class attribute specifies the type of the bean
<bean id="firstBean" class="com.training.Example">
<property name="empname">
<value>ramesh</value>
</property>
<property name="empid"><value>100</value></property>
</bean>
</beans>

31
Injecting Simple Values–XML File

 Each bean is defined using <bean> tag under the root of the <beans>
tag
 The id attribute is used to give the bean its default name
 The class attribute specifies the type of the bean
<bean id="firstBean" class="com.training.Example">
<property name="empname">
<value>ramesh</value>
</property>
<property name="empid"><value>100</value></property>
</bean>
</beans>

32
Spring Application

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class TestExample {
public static void main(String[] args) {
BeanFactory bfact = new XmlBeanFactory(new
FileSystemResource("mybean.xml"));
Example exObj = (Example)bfact.getBean("firstBean");
System.out.println(exObj.getEmpid());
System.out.println(exObj.getEmpname());
}
}

33
Injection Parameter Types

 Spring supports various kinds of injection parameters
• Simple values
• Beans in the same factory
• Beans in another factory
• Collections
• Externally defined properties
 You can use these types for both setter or constructor injections

34
Injecting Bean into the same Factory

 Used when you need to inject one bean into another (target bean)
 Configure both beans first
 Configure an injection using <ref> tag in the target bean's <property>
or <constructor-arg>
 The type being injected does not have to be the exact type defined
on the target
 if the type defined on the target is an interface, the type being
injected must be an implementation of it
 if the type defined on the target is a class, the type being injected can
be the same type or sub-type

35
Constructor Injection

 All dependencies injected via constructor arguments
– Requires potentially complex constructor argument lists
 Avoids reliance on get/set naming conventions
– e.g. addStateObserver()
 Less flexible initialisation
– Need a constructor per configuration option
 Can be difficult to understand
– Rely on ordering of parameters

36
Constructor Dependency Injection
(code snippet)
public class Invoice {
private Items item;
private String customer;
private double amount;
public Invoice(Items item)
{
this.item = item;
}
public Invoice()
{
super();
}
// Set/Get Methods
}

public class Items {
private int itemno;
private String itemname;
public Items() {
super();
}
// Set/Get Methods
}

37
Constructor Dependency Injection
(code snippet)
public class TestConstDepend {
public static void main(String[] args) {
BeanFactory bf = new XmlBeanFactory(new
FileSystemResource("mybeandef.xml"));
Invoice inv = (Invoice)bf.getBean("Invoice");
System.out.println(inv.getItem());
System.out.println(inv.getCustomer());
System.out.println(inv.getAmount());
}
}

38
Setter Injection
 All dependencies injected via setter methods
– No need for constructors
 Allows flexible initialisation
– Any set of properties can be initialised
 Named properties allow for readable configuration data
– Clear what is being injected
 Requires JavaBean conventions to be followed
– Non standard method names are problematic
 Can result in invalid object configurations
– Need post initialisation checking methods

39
Setter Injection (code snippet)
public class Policy {
private int policyCode;
private String policyName;
public Policy(int policyCode,
String policyName) {
this.policyCode =
policyCode;
this.policyName =
policyName;
}
public Policy() {
super();
}
//SET-GET Methods
}

public class Insurance {
private int policynumber;
private Policy policyData;
public Policy getPolicyData() {
return policyData;
}
public void
setPolicyData(Policy
policyData) {
this.policyData =
policyData;
}
//SET-GET Methods
}

40
Setter Injection (code snippet)
public class TestSetterDependcy {
public static void main(String[] args) {
BeanFactory beanFact = new XmlBeanFactory
(new FileSystemResource("myBean.xml"));
Insurance ins =(Insurance)beanFact.getBean("Insurance");
System.out.println("Policy Number"+ins.getPolicynumber());
System.out.println("Policy Code“ +
ins.getPolicyData().getPolicyCode());
System.out.println("Policy Holder Name"+
ins.getPolicyData().getPolicyName());
}
}

41
Setter Injection (code snippet)
<beans>
<bean id="Insurance" class="com.training.Insurance">
<property name="policynumber“ <value>2345</value></property>
<property name="policyData"><ref local="Policy"/></property>
</bean>
<bean id="Policy" class="com.training.Policy">
<property name="policyCode"><value>100</value></property>
<property name="policyName"><value>Life
Insurance</value></property>
</bean>
</beans>

42
Thank You

43

Weitere ähnliche Inhalte

Was ist angesagt?

PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootJosué Neis
 
Java spring framework
Java spring frameworkJava spring framework
Java spring frameworkRajiv Gupta
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action Alex Movila
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepGuo Albert
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionDinesh Sharma
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudEberhard Wolff
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVCDzmitry Naskou
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with SpringJoshua Long
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionRichard Paul
 

Was ist angesagt? (20)

PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
 
Java spring framework
Java spring frameworkJava spring framework
Java spring framework
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency Injection
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring Cloud
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 

Andere mochten auch

Dependency Injection And Ioc Containers
Dependency Injection And Ioc ContainersDependency Injection And Ioc Containers
Dependency Injection And Ioc ContainersTim Murphy
 
Enterprise java evolució, avagy java ee (
Enterprise java evolució, avagy java ee (Enterprise java evolució, avagy java ee (
Enterprise java evolució, avagy java ee (Attila Balogh-Biró
 
Dependency Injection in Spring in 10min
Dependency Injection in Spring in 10minDependency Injection in Spring in 10min
Dependency Injection in Spring in 10minCorneil du Plessis
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax BasicsRichard Paul
 
Spring dependency injection
Spring dependency injectionSpring dependency injection
Spring dependency injectionsrmelody
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right wayThibaud Desodt
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency InjectionTheo Jungeblut
 
Java EE vs Spring Framework
Java  EE vs Spring Framework Java  EE vs Spring Framework
Java EE vs Spring Framework Rohit Kelapure
 

Andere mochten auch (9)

Dependency Injection And Ioc Containers
Dependency Injection And Ioc ContainersDependency Injection And Ioc Containers
Dependency Injection And Ioc Containers
 
Enterprise java evolució, avagy java ee (
Enterprise java evolució, avagy java ee (Enterprise java evolució, avagy java ee (
Enterprise java evolució, avagy java ee (
 
Dependency Injection in Spring in 10min
Dependency Injection in Spring in 10minDependency Injection in Spring in 10min
Dependency Injection in Spring in 10min
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
Spring dependency injection
Spring dependency injectionSpring dependency injection
Spring dependency injection
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency Injection
 
Java EE vs Spring Framework
Java  EE vs Spring Framework Java  EE vs Spring Framework
Java EE vs Spring Framework
 
IoC and Mapper in C#
IoC and Mapper in C#IoC and Mapper in C#
IoC and Mapper in C#
 

Ähnlich wie Spring Framework Guide

Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkDineesha Suraweera
 
Session 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansSession 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansPawanMM
 
Spring Fa Qs
Spring Fa QsSpring Fa Qs
Spring Fa Qsjbashask
 
Spring (1)
Spring (1)Spring (1)
Spring (1)Aneega
 
Spring framework
Spring frameworkSpring framework
Spring frameworkKani Selvam
 
Introduction to j2 ee frameworks
Introduction to j2 ee frameworksIntroduction to j2 ee frameworks
Introduction to j2 ee frameworksMukesh Kumar
 
Spring framework-tutorial
Spring framework-tutorialSpring framework-tutorial
Spring framework-tutorialvinayiqbusiness
 
Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2javatrainingonline
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkASG
 
Spring Basics
Spring BasicsSpring Basics
Spring BasicsEmprovise
 
스프링 프레임워크
스프링 프레임워크스프링 프레임워크
스프링 프레임워크Yoonki Chang
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking TourJoshua Long
 

Ähnlich wie Spring Framework Guide (20)

Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Session 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansSession 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI Beans
 
Spring 2
Spring 2Spring 2
Spring 2
 
Spring Fa Qs
Spring Fa QsSpring Fa Qs
Spring Fa Qs
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Introduction to j2 ee frameworks
Introduction to j2 ee frameworksIntroduction to j2 ee frameworks
Introduction to j2 ee frameworks
 
Spring framework-tutorial
Spring framework-tutorialSpring framework-tutorial
Spring framework-tutorial
 
Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2
 
Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2
 
Spring
SpringSpring
Spring
 
Spring
SpringSpring
Spring
 
Spring
SpringSpring
Spring
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Java spring ppt
Java spring pptJava spring ppt
Java spring ppt
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
 
스프링 프레임워크
스프링 프레임워크스프링 프레임워크
스프링 프레임워크
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking Tour
 

Kürzlich hochgeladen

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Kürzlich hochgeladen (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

Spring Framework Guide

  • 1. Spring Framework Prepared & Presented by Arjun 1
  • 2. Know your trainer Name: Arjun Phone : +91 9691053479 Email: thakurarjun247@gmail.com  Freelance corporate trainer.  More than 2 years of strong hands-on experience in top MNCs in Java and related technologies.  More than 2 years of experience as a Java trainer. Clients / Previous Employers: 2
  • 3. Agenda Topics to be covered are:      Introduction to Spring framework Benefits of Spring framework Spring framework architecture Inversion of Control (IoC) Dependency Injection (DI) 3
  • 4. Spring Framework  Light-weight comprehensive framework for building Java SE and Java EE applications  Created by Rod Johnson  JavaBeans-based configuration management, applying Inversionof-Control principles, specifically using the Dependency Injection technique • Reduce dependencies of components on specific implmentation of other components. • A core bean factory, which is usable globally  Generic abstraction layer for database transaction management 4
  • 5. Key Features  Built-in generic strategies for JTA and a single JDBC DataSource  This removes the dependency on a Java EE environment for transaction support.  Integration with persistence frameworks Hibernate, JDO and iBATIS.  MVC web application framework, built on core Spring functionality,  supporting many technologies for generating views, including JSP.  Extensive aspect-oriented programming (AOP) framework to provide  services such as transaction management.  As with the Inversion-of-Control parts of the system, this aims to improve the modularity of systems created using the framework. 5
  • 6. Using Spring  Wiring of components through Dependency Injection  Promotes de-coupling among the parts that make the application  Test-Driven Development (TDD)  POJO classes can be tested without being tied up with the framework  Declarative programming through AOP  Easily configured aspects, esp. transaction support  Integration with other technologies  EJB for J2EE  Hibernate, iBatis, JDBC (for data access)  Velocity (for presentation)  Struts and WebWork (For web) 6
  • 8. Core Package  The fundamental part which provides the IoC and Dependency Injection features  BeanFactory, provides a sophisticated implementation of the factory pattern  Removes the need for programmatic singletons  Decouple the configuration and specification of dependencies in program logic. 8
  • 9. Context Package  Provides a way to access objects in a framework-style  Inherits its features from the beans package and adds support for • internationalization (I18N) • event-propagation • resource-loading • transparent creation of contexts by 9
  • 10. DAO Package  Provides a JDBC-abstraction layer that removes the need to do tedious  JDBC coding and parsing of database-vendor specific error codes  Programmatic as well as declarative transaction management for • classes implementing special interfaces • POJOs 10
  • 11. ORM Package  The ORM package provides integration layers for popular objectrelational mapping APIs, including JPA, JDO, Hibernate, and iBatis.  Using the ORM package you can use all those O/R-mappers in combination with all the other features Spring offers, such as the simple declarative transaction management feature mentioned previously 11
  • 12. AOP Package  Spring's AOP package provides an AOP Alliance-compliant aspectoriented programming implementation • method-interceptors and pointcuts to cleanly decouple code implementing functionality that should logically speaking be separated  Using source-level metadata functionality you can also incorporate all kinds of behavioral information into your code 12
  • 13. MVC Package  Web package provides features, such as • multipart file-upload functionality, • the initialization of the IoC container using servlet listeners • A web-oriented application context. • Can be used together with WebWork or Struts,  Spring's MVC package provides a Model-View-Controller (MVC)  implementation for web applications  Provides a clean separation between domain model code and web forms, and allows all the other features of the Spring Framework. 13
  • 14. IoC Container      Introduction Basic Containers and Beans Dependencies The Application Context Developing a Spring Application 14
  • 15. Inversion of Control  The Spring IoC container makes use of Java POJO classes and configuration metadata.  It produces a fully configured and executable system or application. 15
  • 16. Introduction to IoC  Traditional software is developed with the application code “in control” • The application defines the “main”function/method/entry point • Calls the application’s components to perform processing  Frameworks invert this relationship and call the application code • “Don’t call us we’ll call you” • Framework provides the “main”function/method/entry point • Application code fits into the framework and is called when the framework decides.  A particular variant of IoC is “dependency injection” 16
  • 17. Dependency Injection  Most frameworks use the “Service Lookup” approach to allow application code to find its dependencies. • e.g. J2EE code looks up resources via JNDI • CORBA applications find services via a Naming Service • The lookup mechanism is hard coded into the application code  Dependency Injection frameworks supply the resources that a component needs when initialising it • Component declares resources required (usually as interface types) • Framework configuration defines concrete instances to use • Framework passes component the concrete resources at load time  “IoC containers” are “Dependency Injection” containers 17
  • 18. Service Lookup vs. Dependency Injection 18
  • 19. IoC Container  The org.springframework.beans and org.springframework.context packages provide the basis for the Spring Framework's IoC container.  BeanFactory interface provides an advanced configuration mechanism capable of managing  objects of any nature.  ApplicationContext interface , a sub interface of BeanFactory is used for • Easier integration with Spring's AOP features, • Message resource handling (in internationalization), • Event propagation • Specific contexts such as the WebApplicationContext 19
  • 20. Container and Beans  A bean is simply an object that is instantiated, assembled and otherwise managed by a Spring IoC container  The beans, and the dependencies between them, are reflected in the configuration metadata used by a container.  org.springframework.beans.factory.BeanFactory is the representation of the Spring IoC container, it’s responsible for: • containing and managing beans, • instantiating or sourcing application objects • configuring such objects • assembling the dependencies between objects. 20
  • 21. The Container  There are a number of implementations of the BeanFactory interface  The most commonly used BeanFactory implementation is the XmlBeanFactory class.  The XmlBeanFactory takes the XML configuration metadata and uses it to create a fully configured system or application. 21
  • 22. Configuration Meta Data  The meta-data informs the Spring container as to how to “instantiate, configure, and assemble *the objects in your application+”.  XML-based metadata is the most commonly used form of configuration metadata.  Configuration consists of at least one bean definition that the container must manage, but could be more than one bean definition.  When using XML-based configuration metadata, these beans are configured as <bean/> elements inside a top-level <beans/> element. 22
  • 23. Simple XML Configuration <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans2.5.xsd"> <bean id="..." class="..."> <!--collaborators and configuration for this bean go here --> </bean> <bean id="..." class="..."> <!--collaborators and configuration for this bean go here --> </bean> <!--more bean definitions go here --> </beans> 23
  • 24. Instantiating a Container ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {"services.xml", "daos.xml"}); // an ApplicationContext is also a BeanFactory (via inheritance) BeanFactory factory = context; 24
  • 25. The Bean  The container manages the beans , and they are are created using the configuration metadata.  Bean definitions are represented as BeanDefinition objects, which contain the following metadata:  package-qualified class name: typically this is the actual implementation class of the bean being defined.  bean behavioral configuration elements, • which state how the bean should behave in the container (scope, lifecycle callbacks etc.,).  references to other beans • which are needed for the bean to do its work; these references are also called collaborators or dependencies.  other configuration settings • An example would be the number of connections to use in a bean that manages a connection pool, or the size limit of the pool. 25
  • 26. Benefits of Dependency Injection  Flexible • Avoid adding lookup code in business logic  Testable • No need to depend on external resources or containers for testing  Maintainable • Promotes a consistent approach across all applications and teams • Allows reuse in different application environments by changing configuration files instead of code 26
  • 27. Dependency Injection     BeanFactory interface XmlBeanFactory implementation Bean configuration file Constructor dependency Injection • Dependencies are provided through the constructors of the component  Setter dependency injection • Dependencies are provided through the JavaBeanstyle setter methods of the component • More popular than Constructor dependency injection  Beans  Injection Parameters 27
  • 28. BeanFactory Class  BeanFactory object is responsible for managing beans and their dependencies  Your application interacts with Spring's DI container through BeanFactory interface • BeanFactory object has to be created by the application typically XmlBeanFactory • BeanFactory object, when it gets created, read bean configuration file and performs the wiring • Once created, the application can access the beans via BeanFactory interface  XmlBeanFactory • Convenience extension of DefaultListableBeanFactory that reads bean definitions from an XML document 28
  • 29. Beans  The term “bean” is used to refer any component managed by the BeanFactory  The “beans” are in the form of JavaBeans (in most cases) • no arg constructor • getter and setter methods for the properties  Beans are singletons by default  Properties • the beans may be simple values or references to other beans 29
  • 30. The Bean – A Java Class public class Example { private int empid; private String empname; public int getEmpid() { return empid; } public void setEmpid(int empid) { this.empid = empid; } public String getEmpname() { return empname; } public void setEmpname(String empname) { this.empname = empname; } public Example() {super();}} // no arg constructor 30
  • 31. Injecting Simple Values–XML File  Each bean is defined using <bean> tag under the root of the <beans> tag  The id attribute is used to give the bean its default name  The class attribute specifies the type of the bean <bean id="firstBean" class="com.training.Example"> <property name="empname"> <value>ramesh</value> </property> <property name="empid"><value>100</value></property> </bean> </beans> 31
  • 32. Injecting Simple Values–XML File  Each bean is defined using <bean> tag under the root of the <beans> tag  The id attribute is used to give the bean its default name  The class attribute specifies the type of the bean <bean id="firstBean" class="com.training.Example"> <property name="empname"> <value>ramesh</value> </property> <property name="empid"><value>100</value></property> </bean> </beans> 32
  • 33. Spring Application import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.FileSystemResource; public class TestExample { public static void main(String[] args) { BeanFactory bfact = new XmlBeanFactory(new FileSystemResource("mybean.xml")); Example exObj = (Example)bfact.getBean("firstBean"); System.out.println(exObj.getEmpid()); System.out.println(exObj.getEmpname()); } } 33
  • 34. Injection Parameter Types  Spring supports various kinds of injection parameters • Simple values • Beans in the same factory • Beans in another factory • Collections • Externally defined properties  You can use these types for both setter or constructor injections 34
  • 35. Injecting Bean into the same Factory  Used when you need to inject one bean into another (target bean)  Configure both beans first  Configure an injection using <ref> tag in the target bean's <property> or <constructor-arg>  The type being injected does not have to be the exact type defined on the target  if the type defined on the target is an interface, the type being injected must be an implementation of it  if the type defined on the target is a class, the type being injected can be the same type or sub-type 35
  • 36. Constructor Injection  All dependencies injected via constructor arguments – Requires potentially complex constructor argument lists  Avoids reliance on get/set naming conventions – e.g. addStateObserver()  Less flexible initialisation – Need a constructor per configuration option  Can be difficult to understand – Rely on ordering of parameters 36
  • 37. Constructor Dependency Injection (code snippet) public class Invoice { private Items item; private String customer; private double amount; public Invoice(Items item) { this.item = item; } public Invoice() { super(); } // Set/Get Methods } public class Items { private int itemno; private String itemname; public Items() { super(); } // Set/Get Methods } 37
  • 38. Constructor Dependency Injection (code snippet) public class TestConstDepend { public static void main(String[] args) { BeanFactory bf = new XmlBeanFactory(new FileSystemResource("mybeandef.xml")); Invoice inv = (Invoice)bf.getBean("Invoice"); System.out.println(inv.getItem()); System.out.println(inv.getCustomer()); System.out.println(inv.getAmount()); } } 38
  • 39. Setter Injection  All dependencies injected via setter methods – No need for constructors  Allows flexible initialisation – Any set of properties can be initialised  Named properties allow for readable configuration data – Clear what is being injected  Requires JavaBean conventions to be followed – Non standard method names are problematic  Can result in invalid object configurations – Need post initialisation checking methods 39
  • 40. Setter Injection (code snippet) public class Policy { private int policyCode; private String policyName; public Policy(int policyCode, String policyName) { this.policyCode = policyCode; this.policyName = policyName; } public Policy() { super(); } //SET-GET Methods } public class Insurance { private int policynumber; private Policy policyData; public Policy getPolicyData() { return policyData; } public void setPolicyData(Policy policyData) { this.policyData = policyData; } //SET-GET Methods } 40
  • 41. Setter Injection (code snippet) public class TestSetterDependcy { public static void main(String[] args) { BeanFactory beanFact = new XmlBeanFactory (new FileSystemResource("myBean.xml")); Insurance ins =(Insurance)beanFact.getBean("Insurance"); System.out.println("Policy Number"+ins.getPolicynumber()); System.out.println("Policy Code“ + ins.getPolicyData().getPolicyCode()); System.out.println("Policy Holder Name"+ ins.getPolicyData().getPolicyName()); } } 41
  • 42. Setter Injection (code snippet) <beans> <bean id="Insurance" class="com.training.Insurance"> <property name="policynumber“ <value>2345</value></property> <property name="policyData"><ref local="Policy"/></property> </bean> <bean id="Policy" class="com.training.Policy"> <property name="policyCode"><value>100</value></property> <property name="policyName"><value>Life Insurance</value></property> </bean> </beans> 42