SlideShare a Scribd company logo
1 of 30
1
Spring Framework
• A popular and stable Java application
framework for enterprise development
– Ubiquitous for Java development
– Well established in enterprise Java apps
– Time tested and proven reliable
• A primary purpose is to reduce
dependencies and even introduce
negative dependencies
– Different from almost every other framework out there
– Part of the reason it has been adopted so quickly
URL: http://www.springframework.org/
2
Spring code structure
• Spring code base is proven to be well
structured (possibly the best)
– http://chris.headwaysoftware.com/2006/07/springs_structu.html
• Analysis using Structure 101
• 139 packages
• No dependency cycles
3
More Spring
• Considered an alternative / replacement
for the Enterprise JavaBean (EJB) model
• Flexible
– Programmers decide how to program
• Not exclusive to Java (e.g. .NET)
• Solutions to typical coding busywork
– JDBC
– LDAP
– Web Services
URL: http://en.wikipedia.org/wiki/Spring_framework
4
What does Spring offer?
• Dependency Injection
– Also known as IoC (Inversion of Control)
• Aspect Oriented Programming
– Runtime injection-based
• Portable Service Abstractions
– The rest of spring
• ORM, DAO, Web MVC, Web, etc.
• Allows access to these without knowing how they
actually work
5
Dependency Injection defined
• Method to create needed dependencies or look
them up somehow without doing it in the
dependent code
– Often called Inversion of Control (IoC)
• IoC injects needed dependencies into the object
instead
– Setters or Contructor
• Primary goal is reduction of dependencies in
code
– an excellent goal in any case
– This is the central part of Spring
URL: http://en.wikipedia.org/wiki/Inversion_of_Control
6
Aspect Oriented Programming
defined
• Attempts to separate concerns, increase
modularity, and decrease redundancy
– Separation of Concerns (SoC)
• Break up features to minimize overlap
– Don’t Repeat Yourself (DRY)
• Minimize code duplication
– Cross-Cutting Concerns
• Program aspects that affect many others (e.g. logging)
• AspectJ is the top AOP package
– Java like syntax, IDE integration
URL: http://en.wikipedia.org/wiki/Aspect-oriented_programming
7
Portable Service Abstractions
defined
• Services that easily move between
systems without heavy reworking
– Ideally easy to run on any system
– Abstraction without exposing service
dependencies
• LDAP access without knowing what LDAP is
• Database access without typical JDBC hoops
• Basically everything in Spring that is not
IoC or AOP
8
What is a bean?
• Typical java bean with a unique id
• In spring there are basically two types
– Singleton
• One instance of the bean created and referenced
each time it is requested
– Prototype (non-singleton)
• New bean created each time
• Same as new ClassName()
• Beans are normally created by Spring as
late as possible
9
What is a bean definition?
• Defines a bean for Spring to manage
– Key attributes
• class (required): fully qualified java class name
• id: the unique identifier for this bean
• configuration: (singleton, init-method, etc.)
• constructor-arg: arguments to pass to the constructor at
creation time
• property: arguments to pass to the bean setters at creation
time
• Collaborators: other beans needed in this bean (a.k.a
dependencies), specified in property or constructor-arg
• Typically defined in an XML file
10
Sample bean definition
<bean id="exampleBean" class=”org.example.ExampleBean">
<property name="beanOne"><ref bean="anotherExampleBean"/></property>
<property name="beanTwo"><ref bean="yetAnotherBean"/></property>
<property name="integerProperty"><value>1</value></property>
</bean>
public class ExampleBean {
private AnotherBean beanOne;
private YetAnotherBean beanTwo;
private int i;
public void setBeanOne(AnotherBean beanOne) {
this.beanOne = beanOne; }
public void setBeanTwo(YetAnotherBean beanTwo) {
this.beanTwo = beanTwo; }
public void setIntegerProperty(int i) {
this.i = i; }
…
}
11
What is a bean factory?
• Often seen as an ApplicationContext
– BeanFactory is not used directly often
– ApplicationContext is a complete superset of bean
factory methods
• Same interface implemented
• Offers a richer set of features
• Spring uses a BeanFactory to create, manage
and locate “beans” which are basically instances
of a class
– Typical usage is an XML bean factory which allows
configuration via XML files
12
• Beans are created in order based on the dependency
graph
– Often they are created when the factory loads the definitions
– Can override this behavior in bean
<bean class=“className” lazy-init=“true” />
– You can also override this in the factory or context but this is
not recommended
• Spring will instantiate beans in the order required by
their dependencies
1. app scope singleton - eagerly instantiated at container startup
2. lazy dependency - created when dependent bean created
3. VERY lazy dependency - created when accessed in code
How are beans created?
13
How are beans injected?
• A dependency graph is constructed based
on the various bean definitions
• Beans are created using constructors
(mostly no-arg) or factory methods
• Dependencies that were not injected via
constructor are then injected using setters
• Any dependency that has not been
created is created as needed
14
Multiple bean config files
• There are 3 ways to load multiple bean config files
(allows for logical division of beans)
– Load multiple config files from web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/WEB-INF/spring-config.xml, classpath:/WEB-
INF/applicationContext.xml</param-value>
</context-param>
– Use the import tag
<import resource="services.xml"/>
– Load multiple config files using Resources in the
application context constructor
• Recommended by the spring team
• Not always possible though
ClassPathXmlApplicationContext appContext = new
ClassPathXmlApplicationContext( new String[]
{"applicationContext.xml", "applicationContext-
part2.xml"});
15
Bean properties?
• The primary method of dependency injection
• Can be another bean, value, collection, etc.
<bean id="exampleBean" class="org.example.ExampleBean">
<property name="anotherBean">
<ref bean="someOtherBean" />
</property>
</bean>
• This can be written in shorthand as follows
<bean id="exampleBean" class="org.example.ExampleBean">
<property name="anotherBean" ref="someOtherBean" />
</bean>
16
Anonymous vs ID
• Beans that do not need to be referenced
elsewhere can be defined anonymously
• This bean is identified (has an id) and can be
accessed to inject it into another bean
• This bean is anonymous (no id)
<bean class="org.example.ExampleBean">
<property name="anotherBean" ref="someOtherBean" />
</bean>
<bean id="exampleBean" class="org.example.ExampleBean">
<property name="anotherBean" ref="someOtherBean" />
</bean>
17
What is an inner bean?
• It is a way to define a bean needed by
another bean in a shorthand way
– Always anonymous (id is ignored)
– Always prototype (non-singleton)
<bean id="outer" class="org.example.SomeBean">
<property name="person">
<bean class="org.example.PersonImpl">
<property name="name"><value>Aaron</value></property>
<property name="age"><value>31</value></property>
</bean>
</property>
</bean>
18
Bean init-method
• The init method runs AFTER all bean
dependencies are loaded
– Constructor loads when the bean is first
instantiated
– Allows the programmer to execute code once all
dependencies are present
<bean id="exampleBean" class=”org.example.ExampleBean"
init-method=”init” />
public class ExampleBean {
public void init() {
// do something
}
}
19
Bean values
• Spring can inject more than just other beans
• Values on beans can be of a few types
– Direct value (string, int, etc.)
– Collection (list, set, map, props)
– Bean
– Compound property
<bean class="org.example.ExampleBean">
<property name="email">
<value>azeckoski@gmail.com</value>
</property>
</bean>
Example of injecting a string value
20
Abstract (parent) beans
• Allows definition of part of a bean which can
be reused many times in other bean
definitions
<bean id="abstractBean" abstract="true"
class="org.example.ParentBean">
<property name="name" value="parent-AZ"/>
<property name="age" value="31"/>
</bean>
<bean id="childBean"
class="org.example.ChildBean"
parent="abstractBean" init-method="init">
<property name="name" value="child-AZ"/>
</bean>
The parent bean
defines 2 values (name,
age)
The child bean uses the
parent age value (31)
The child bean
overrides the parent
name value (from parent-
AZ to child-AZ)
Parent bean could not
be injected, child could
21
AOP in Spring
• Provides way to create declarative services
and custom aspects
• Transaction management is the most
common aspect (or concern)
• Spring handles AOP via advisors or
interceptors
– Interception point is a joinpoint
– A set of joinpoints are called a pointcut
• pointcuts are key to Spring AOP, they allow intercepts
without explicit knowledge of the OO hierarchy
– Action taken by an interceptor is called advice
22
AOP advice types
• Around
– Most common and powerful
– Execute code before and after joinpoint
• Before
– Executes before joinpoint, cannot stop execution
• Throws
– Executes code if exception is thrown
• After return
– Executes code after normal joinpoint execution
23
Spring AOP key points
• Pure java implementation
• Allows method interception
– No field or property intercepts yet
• AOP advice is specified using typical
bean definitions
– Closely integrates with Spring IoC
• Proxy based AOP
– J2SE dynamic proxies or CGLIB proxies
• Not a replacement for AspectJ
24
Example transaction proxy
<bean id="daoBeanTarget" class="org.example.dao.impl.DaoImpl">
<property name="sessionFactory"><ref bean="mySessionFactory"/></property>
</bean>
<bean id="daoBean"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="transactionManager"/>
<property name="target" ref="daoBeanTarget"/>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
• This wraps a transaction interceptor around a DAO
25
Working example
• Let’s look at some example code pre and
post spring
– Simple application that allows a user to add,
remove, and list a set of strings
• Pre spring code
– Programmers Cafe - Example App
• Post spring code
– Programmers Cafe - Example App Spring
26
Example App
• The example app is a simple command
line Java app which is meant to
demonstrate a reasonable dependency
structure
• This app allows a user to save, delete,
and list a set of strings associated with
their username
27
Example App Structure
• Alpha is the main class
• Bravo handles user
interaction
• Charlie handles
application logic
• Delta handles data
access
• Dependency graph is
non-cyclical
– No A => B => C => A
Alpha
Charlie
Bravo
Delta
A B = A depends on B
DeltaImpl
28
Non-spring version
• Involves using new to create needed
dependencies
• Each class must know about the
dependencies that it needs
• Singletons have to be created and handed to
the classes that need them at the same time
or you need a static way to access them (or a
framework)
• Tightly coupled code structure
29
Spring version
• No more new use
• Classes only have to know about the
interface
– or class if no interface available
• Singletons easy to handle
• Loose coupling allows flexible changes
30
Questions?
• Spring framework
– http://www.springframework.org/

More Related Content

What's hot

What's hot (11)

Quartz component in mule
Quartz component in muleQuartz component in mule
Quartz component in mule
 
MuleSoft ESB Message Enricher
MuleSoft ESB Message Enricher MuleSoft ESB Message Enricher
MuleSoft ESB Message Enricher
 
Groovy example in mule
Groovy example in muleGroovy example in mule
Groovy example in mule
 
MuleSoft ESB scatter-gather and base64
MuleSoft ESB scatter-gather and base64MuleSoft ESB scatter-gather and base64
MuleSoft ESB scatter-gather and base64
 
For each component in mule
For each component in muleFor each component in mule
For each component in mule
 
Passing java arrays in oracle stored procedure from mule esb flow
Passing java arrays in oracle stored procedure from mule esb flowPassing java arrays in oracle stored procedure from mule esb flow
Passing java arrays in oracle stored procedure from mule esb flow
 
Integrate with database by groovy
Integrate with database by groovyIntegrate with database by groovy
Integrate with database by groovy
 
Junit in mule demo
Junit in mule demo Junit in mule demo
Junit in mule demo
 
Mule esb
Mule esbMule esb
Mule esb
 
Expression filter in Mule
Expression filter in MuleExpression filter in Mule
Expression filter in Mule
 
MuleSoft ESB - CSV File to Database
MuleSoft ESB - CSV File to DatabaseMuleSoft ESB - CSV File to Database
MuleSoft ESB - CSV File to Database
 

Viewers also liked

Viewers also liked (13)

Mule esb data weave multi input data
Mule esb data weave multi input dataMule esb data weave multi input data
Mule esb data weave multi input data
 
Mule and web services
Mule and web servicesMule and web services
Mule and web services
 
Splitter and Collection Aggregator With Mulesoft
Splitter and Collection Aggregator With Mulesoft Splitter and Collection Aggregator With Mulesoft
Splitter and Collection Aggregator With Mulesoft
 
Spring aop concepts
Spring aop conceptsSpring aop concepts
Spring aop concepts
 
Getting Started with Spring Framework
Getting Started with Spring FrameworkGetting Started with Spring Framework
Getting Started with Spring Framework
 
Mulesoft ppt
Mulesoft pptMulesoft ppt
Mulesoft ppt
 
Java and services code lab spring boot and spring data using mongo db
Java and services code lab spring boot and spring data using mongo dbJava and services code lab spring boot and spring data using mongo db
Java and services code lab spring boot and spring data using mongo db
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Message Chunk Splitter And Aggregator With MuleSoft
Message Chunk Splitter And Aggregator With MuleSoftMessage Chunk Splitter And Aggregator With MuleSoft
Message Chunk Splitter And Aggregator With MuleSoft
 
Digital Businesses of the Future
Digital Businesses of the Future Digital Businesses of the Future
Digital Businesses of the Future
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 

Similar to Spring introduction

Spring framework
Spring frameworkSpring framework
Spring framework
Ajit Koti
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
Guo Albert
 

Similar to Spring introduction (20)

Spring, web service, web server, eclipse by a introduction sandesh sharma
Spring, web service, web server, eclipse by a introduction sandesh sharmaSpring, web service, web server, eclipse by a introduction sandesh sharma
Spring, web service, web server, eclipse by a introduction sandesh sharma
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
 
스프링 프레임워크
스프링 프레임워크스프링 프레임워크
스프링 프레임워크
 
Lo nuevo en Spring 3.0
Lo nuevo  en Spring 3.0Lo nuevo  en Spring 3.0
Lo nuevo en Spring 3.0
 
BP-6 Repository Customization Best Practices
BP-6 Repository Customization Best PracticesBP-6 Repository Customization Best Practices
BP-6 Repository Customization Best Practices
 
01 spring-intro
01 spring-intro01 spring-intro
01 spring-intro
 
Apache maven and its impact on java 9 (Java One 2017)
Apache maven and its impact on java 9 (Java One 2017)Apache maven and its impact on java 9 (Java One 2017)
Apache maven and its impact on java 9 (Java One 2017)
 
Spring
SpringSpring
Spring
 
Spring
SpringSpring
Spring
 
Spring
SpringSpring
Spring
 
Java spring framework
Java spring frameworkJava spring framework
Java spring framework
 
Skillwise-Spring framework 1
Skillwise-Spring framework 1Skillwise-Spring framework 1
Skillwise-Spring framework 1
 
Spring 3.1 in a Nutshell - JAX London 2011
Spring 3.1 in a Nutshell - JAX London 2011Spring 3.1 in a Nutshell - JAX London 2011
Spring 3.1 in a Nutshell - JAX London 2011
 
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen
Spring Day | Spring 3.1 in a Nutshell | Sam BrannenSpring Day | Spring 3.1 in a Nutshell | Sam Brannen
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking Tour
 
Hybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbaiHybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbai
 
Spring boot for buidling microservices
Spring boot for buidling microservicesSpring boot for buidling microservices
Spring boot for buidling microservices
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Recently uploaded (20)

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 

Spring introduction

  • 1. 1 Spring Framework • A popular and stable Java application framework for enterprise development – Ubiquitous for Java development – Well established in enterprise Java apps – Time tested and proven reliable • A primary purpose is to reduce dependencies and even introduce negative dependencies – Different from almost every other framework out there – Part of the reason it has been adopted so quickly URL: http://www.springframework.org/
  • 2. 2 Spring code structure • Spring code base is proven to be well structured (possibly the best) – http://chris.headwaysoftware.com/2006/07/springs_structu.html • Analysis using Structure 101 • 139 packages • No dependency cycles
  • 3. 3 More Spring • Considered an alternative / replacement for the Enterprise JavaBean (EJB) model • Flexible – Programmers decide how to program • Not exclusive to Java (e.g. .NET) • Solutions to typical coding busywork – JDBC – LDAP – Web Services URL: http://en.wikipedia.org/wiki/Spring_framework
  • 4. 4 What does Spring offer? • Dependency Injection – Also known as IoC (Inversion of Control) • Aspect Oriented Programming – Runtime injection-based • Portable Service Abstractions – The rest of spring • ORM, DAO, Web MVC, Web, etc. • Allows access to these without knowing how they actually work
  • 5. 5 Dependency Injection defined • Method to create needed dependencies or look them up somehow without doing it in the dependent code – Often called Inversion of Control (IoC) • IoC injects needed dependencies into the object instead – Setters or Contructor • Primary goal is reduction of dependencies in code – an excellent goal in any case – This is the central part of Spring URL: http://en.wikipedia.org/wiki/Inversion_of_Control
  • 6. 6 Aspect Oriented Programming defined • Attempts to separate concerns, increase modularity, and decrease redundancy – Separation of Concerns (SoC) • Break up features to minimize overlap – Don’t Repeat Yourself (DRY) • Minimize code duplication – Cross-Cutting Concerns • Program aspects that affect many others (e.g. logging) • AspectJ is the top AOP package – Java like syntax, IDE integration URL: http://en.wikipedia.org/wiki/Aspect-oriented_programming
  • 7. 7 Portable Service Abstractions defined • Services that easily move between systems without heavy reworking – Ideally easy to run on any system – Abstraction without exposing service dependencies • LDAP access without knowing what LDAP is • Database access without typical JDBC hoops • Basically everything in Spring that is not IoC or AOP
  • 8. 8 What is a bean? • Typical java bean with a unique id • In spring there are basically two types – Singleton • One instance of the bean created and referenced each time it is requested – Prototype (non-singleton) • New bean created each time • Same as new ClassName() • Beans are normally created by Spring as late as possible
  • 9. 9 What is a bean definition? • Defines a bean for Spring to manage – Key attributes • class (required): fully qualified java class name • id: the unique identifier for this bean • configuration: (singleton, init-method, etc.) • constructor-arg: arguments to pass to the constructor at creation time • property: arguments to pass to the bean setters at creation time • Collaborators: other beans needed in this bean (a.k.a dependencies), specified in property or constructor-arg • Typically defined in an XML file
  • 10. 10 Sample bean definition <bean id="exampleBean" class=”org.example.ExampleBean"> <property name="beanOne"><ref bean="anotherExampleBean"/></property> <property name="beanTwo"><ref bean="yetAnotherBean"/></property> <property name="integerProperty"><value>1</value></property> </bean> public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; public void setBeanOne(AnotherBean beanOne) { this.beanOne = beanOne; } public void setBeanTwo(YetAnotherBean beanTwo) { this.beanTwo = beanTwo; } public void setIntegerProperty(int i) { this.i = i; } … }
  • 11. 11 What is a bean factory? • Often seen as an ApplicationContext – BeanFactory is not used directly often – ApplicationContext is a complete superset of bean factory methods • Same interface implemented • Offers a richer set of features • Spring uses a BeanFactory to create, manage and locate “beans” which are basically instances of a class – Typical usage is an XML bean factory which allows configuration via XML files
  • 12. 12 • Beans are created in order based on the dependency graph – Often they are created when the factory loads the definitions – Can override this behavior in bean <bean class=“className” lazy-init=“true” /> – You can also override this in the factory or context but this is not recommended • Spring will instantiate beans in the order required by their dependencies 1. app scope singleton - eagerly instantiated at container startup 2. lazy dependency - created when dependent bean created 3. VERY lazy dependency - created when accessed in code How are beans created?
  • 13. 13 How are beans injected? • A dependency graph is constructed based on the various bean definitions • Beans are created using constructors (mostly no-arg) or factory methods • Dependencies that were not injected via constructor are then injected using setters • Any dependency that has not been created is created as needed
  • 14. 14 Multiple bean config files • There are 3 ways to load multiple bean config files (allows for logical division of beans) – Load multiple config files from web.xml <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/WEB-INF/spring-config.xml, classpath:/WEB- INF/applicationContext.xml</param-value> </context-param> – Use the import tag <import resource="services.xml"/> – Load multiple config files using Resources in the application context constructor • Recommended by the spring team • Not always possible though ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext( new String[] {"applicationContext.xml", "applicationContext- part2.xml"});
  • 15. 15 Bean properties? • The primary method of dependency injection • Can be another bean, value, collection, etc. <bean id="exampleBean" class="org.example.ExampleBean"> <property name="anotherBean"> <ref bean="someOtherBean" /> </property> </bean> • This can be written in shorthand as follows <bean id="exampleBean" class="org.example.ExampleBean"> <property name="anotherBean" ref="someOtherBean" /> </bean>
  • 16. 16 Anonymous vs ID • Beans that do not need to be referenced elsewhere can be defined anonymously • This bean is identified (has an id) and can be accessed to inject it into another bean • This bean is anonymous (no id) <bean class="org.example.ExampleBean"> <property name="anotherBean" ref="someOtherBean" /> </bean> <bean id="exampleBean" class="org.example.ExampleBean"> <property name="anotherBean" ref="someOtherBean" /> </bean>
  • 17. 17 What is an inner bean? • It is a way to define a bean needed by another bean in a shorthand way – Always anonymous (id is ignored) – Always prototype (non-singleton) <bean id="outer" class="org.example.SomeBean"> <property name="person"> <bean class="org.example.PersonImpl"> <property name="name"><value>Aaron</value></property> <property name="age"><value>31</value></property> </bean> </property> </bean>
  • 18. 18 Bean init-method • The init method runs AFTER all bean dependencies are loaded – Constructor loads when the bean is first instantiated – Allows the programmer to execute code once all dependencies are present <bean id="exampleBean" class=”org.example.ExampleBean" init-method=”init” /> public class ExampleBean { public void init() { // do something } }
  • 19. 19 Bean values • Spring can inject more than just other beans • Values on beans can be of a few types – Direct value (string, int, etc.) – Collection (list, set, map, props) – Bean – Compound property <bean class="org.example.ExampleBean"> <property name="email"> <value>azeckoski@gmail.com</value> </property> </bean> Example of injecting a string value
  • 20. 20 Abstract (parent) beans • Allows definition of part of a bean which can be reused many times in other bean definitions <bean id="abstractBean" abstract="true" class="org.example.ParentBean"> <property name="name" value="parent-AZ"/> <property name="age" value="31"/> </bean> <bean id="childBean" class="org.example.ChildBean" parent="abstractBean" init-method="init"> <property name="name" value="child-AZ"/> </bean> The parent bean defines 2 values (name, age) The child bean uses the parent age value (31) The child bean overrides the parent name value (from parent- AZ to child-AZ) Parent bean could not be injected, child could
  • 21. 21 AOP in Spring • Provides way to create declarative services and custom aspects • Transaction management is the most common aspect (or concern) • Spring handles AOP via advisors or interceptors – Interception point is a joinpoint – A set of joinpoints are called a pointcut • pointcuts are key to Spring AOP, they allow intercepts without explicit knowledge of the OO hierarchy – Action taken by an interceptor is called advice
  • 22. 22 AOP advice types • Around – Most common and powerful – Execute code before and after joinpoint • Before – Executes before joinpoint, cannot stop execution • Throws – Executes code if exception is thrown • After return – Executes code after normal joinpoint execution
  • 23. 23 Spring AOP key points • Pure java implementation • Allows method interception – No field or property intercepts yet • AOP advice is specified using typical bean definitions – Closely integrates with Spring IoC • Proxy based AOP – J2SE dynamic proxies or CGLIB proxies • Not a replacement for AspectJ
  • 24. 24 Example transaction proxy <bean id="daoBeanTarget" class="org.example.dao.impl.DaoImpl"> <property name="sessionFactory"><ref bean="mySessionFactory"/></property> </bean> <bean id="daoBean" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager" ref="transactionManager"/> <property name="target" ref="daoBeanTarget"/> <property name="transactionAttributes"> <props> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> • This wraps a transaction interceptor around a DAO
  • 25. 25 Working example • Let’s look at some example code pre and post spring – Simple application that allows a user to add, remove, and list a set of strings • Pre spring code – Programmers Cafe - Example App • Post spring code – Programmers Cafe - Example App Spring
  • 26. 26 Example App • The example app is a simple command line Java app which is meant to demonstrate a reasonable dependency structure • This app allows a user to save, delete, and list a set of strings associated with their username
  • 27. 27 Example App Structure • Alpha is the main class • Bravo handles user interaction • Charlie handles application logic • Delta handles data access • Dependency graph is non-cyclical – No A => B => C => A Alpha Charlie Bravo Delta A B = A depends on B DeltaImpl
  • 28. 28 Non-spring version • Involves using new to create needed dependencies • Each class must know about the dependencies that it needs • Singletons have to be created and handed to the classes that need them at the same time or you need a static way to access them (or a framework) • Tightly coupled code structure
  • 29. 29 Spring version • No more new use • Classes only have to know about the interface – or class if no interface available • Singletons easy to handle • Loose coupling allows flexible changes
  • 30. 30 Questions? • Spring framework – http://www.springframework.org/