SlideShare a Scribd company logo
1 of 29
FPT APTECH COMPUTER EDUCATION HANOI
Spring Framework
2
3
Dependency Injection and
Inversion of Control
4
Bean scopes
• singleton
(Default) Scopes a single bean definition to a single object instance per Spring IoC container.
• prototype
Scopes a single bean definition to any number of object instances.
• request
Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request
has its own instance of a bean created off the back of a single bean definition. Only valid in the
context of a web-aware Spring ApplicationContext.
• session
Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a
web-aware SpringApplicationContext.
• global session
Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when
used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
• custom scope
To integrate your custom scope(s) into the Spring container, you need to implement
the org.springframework.beans.factory.config.Scope interface
Overview
6
Modules
7
Constructor-based dependency
injection
• Constructor-based DI is accomplished by the container invoking a
constructor with a number of arguments
public class SimpleMovieLister {
// the SimpleMovieLister has a dependency on a MovieFinder
private MovieFinder movieFinder;
// a constructor so that the Spring container can 'inject' a MovieFinder
public SimpleMovieLister(MovieFinder movieFinder) {
this.movieFinder = movieFinder; }
}
<bean id=“simpleMovieLister ” class=“example. SimpleMovieLister ”>
<constructor-arg name=“movieFinder”><ref bean=“movieFinder”/>
</bean>
<bean id=“movieFinder” class=“example. MovieFinder”>
Setter-based dependency
injection
• Setter-based DI is accomplished by the container calling setter
methods on your beans after invoking a no-argument constructor or
no-argumentstatic factory method to instantiate your bean.
public class SimpleMovieLister {
// the SimpleMovieLister has a dependency on a MovieFinder
private MovieFinder movieFinder;
public SimpleMovieLister() { }
// a setter method so that the Spring container can 'inject' a MovieFinder
public setMovieFinder (MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
}
<bean id=“simpleMovieLister ” class=“example. SimpleMovieLister ”>
<property name=“movieFinder”><ref bean=“movieFinder”/>
</property>
</bean>
<bean id=“movieFinder” class=“example. MovieFinder”>
Abstract Beans
• Allows definition of part of a bean which can be reused many times in
other bean definitions
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
<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 singleton scope
• The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every
time a request for that specific bean is made. That is, the bean is injected into another bean or you request it
through a getBean() method call on the container. As a rule, use the prototype scope for all stateful beans and
the singleton scope for stateless beans.
• The following diagram illustrates the Spring prototype scope. A data access object (DAO) is not typically
configured as a prototype, because a typical DAO does not hold any conversational state; it was just easier for
this author to reuse the core of the singleton diagram.
<bean id="accountService" class=“DefaultAccountService"/>
<!-- the following is equivalent, though redundant (singleton scope is the
default) --> <bean id="accountService" class=“DefaultAccountService"
scope="singleton“/>
The prototype scope
• The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every
time a request for that specific bean is made. That is, the bean is injected into another bean or you request it
through a getBean() method call on the container. As a rule, use the prototype scope for all stateful beans
and the singleton scope for stateless beans.
• The following diagram illustrates the Spring prototype scope. A data access object (DAO) is not typically
configured as a prototype, because a typical DAO does not hold any conversational state; it was just easier
for this author to reuse the core of the singleton diagram.
<bean id="accountService" class=“DefaultAccountService"
scope="prototype“/>
Request, session, and global session
scopes
• Request scope
The Spring container creates a new instance of the LoginAction bean by using the loginAction bean definition for each and
every HTTP request. That is, the loginAction bean is scoped at the HTTP request level. You can change the internal state of the
instance that is created as much as you want, because other instances created from the same loginAction bean definition will not
see these changes in state; they are particular to an individual request. When the request completes processing, the bean that is
scoped to the request is discarded.
• Session scope
The Spring container creates a new instance of the UserPreferences bean by using the userPreferences bean definition for the
lifetime of a single HTTP Session. In other words, the userPreferences bean is effectively scoped at the HTTP Session level. As
with request-scoped beans, you can change the internal state of the instance that is created as much as you want, knowing that
other HTTP Session instances that are also using instances created from the same userPreferences bean definition do not see these
changes in state, because they are particular to an individual HTTP Session. When the HTTP Session is eventually discarded, the
bean that is scoped to that particular HTTP Session is also discarded.
• Global session scope
The global session scope is similar to the standard HTTP Session scope and applies only in the context of portlet-based web
applications. The portlet specification defines the notion of a global Session that is shared among all portlets that make up a single
portlet web application. Beans defined at the global session scope are scoped (or bound) to the lifetime of the global
portlet Session.
<bean id="loginAction" class="com.foo.LoginAction" scope="request"/>
<bean id="userPreferences" class="com.foo.UserPreferences"
scope="session“/>
<bean id="userPreferences" class="com.foo.UserPreferences"
scope="globalSession”/>
The Spring IOC Container
14
BeanFactory
Container Instantiation
Instantiating a Spring IoC container is easy;
• Resource resource = new FileSystemResource("beans.xml");
– BeanFactory factory = new XmlBeanFactory(resource);
• ClassPathResource resource = new
ClassPathResource("beans.xml");
– BeanFactory factory = new XmlBeanFactory(resource);
• ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] {"applicationContext.xml", "applicationContext-
part2.xml"});
// of course, an ApplicationContext is just a BeanFactory
– BeanFactory factory = (BeanFactory) context;
15
Demo
16
17
Spring AOP
We believe that Aspect-Oriented Programming
(AOP) offers a better solution to many
problems than do existing technologies such
as EJB. The AOP Alliance aims to ensure
interoperability between Java/J2EE AOP
implementations to build a larger AOP
community.
AOP Alliance(http://aopalliance.sourceforge.net/)
Proxy pattern
DEAE / Session 9 19
Decorator pattern
DEAE / Session 9 20
AOP Fundamentals
• Aspect-oriented programming (AOP) provides for
simplified application of cross-cutting concerns
– Transaction management
– Security
– Logging
– Auditing
– Locking
21
AOP concepts
• Aspect: a modularization of a concern that cuts across
multiple classes
• Join point: a point during the execution of a program
• Advice: action taken by an aspect at a particular join point
• Pointcut: a predicate that matches join points
• Introduction: declaring additional methods or fields on behalf
of a type:
• Target object: object being advised by one or more aspects
• AOP proxy: an object created by the AOP framework in order
to implement the aspect contracts
• Weaving: linking aspects with other application types or
objects to create an advised object
22
Types of advice
• Before advice
• After returning advice
• After throwing advice
• After (finally) advice
• Around advice
DEAE / Session 9 23
AOP Proxies
• Spring AOP defaults to using standard J2SE dynamic
proxies for AOP proxies
• Spring AOP can also use CGLIB proxies
DEAE / Session 9 24
@AspectJ support
• @AspectJ refers to a style of declaring aspects as
regular Java classes annotated with Java 5
annotations
• Support configuration with XML
DEAE / Session 9 25
Declaring a pointcut
• execution - for matching method execution join points, this is the
primary pointcut designator you will use when working with Spring
AOP
• within - limits matching to join points within certain types (simply the
execution of a method declared within a matching type when using
Spring AOP)
• this - limits matching to join points (the execution of methods when
using Spring AOP) where the bean reference (Spring AOP proxy) is
an instance of the given type
• target - limits matching to join points (the execution of methods
when using Spring AOP) where the target object (application object
being proxied) is an instance of the given type
• args - limits matching to join points (the execution of methods when
using Spring AOP) where the arguments are instances of the given
types
26
Declaring a pointcut
27
Examples
Declaring Pointcut & Advice
• Declaring A Pointcut
• Declaring advice
<aop:config>
<aop:advisor pointcut=“SystemArchitecture.businessService()" advice-ref="tx-advice"/>
</aop:config>
<tx:advice id="tx-advice">
<tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes>
</tx:advice>
Or
@Pointcut("execution(* com.xyz.someapp.service.*.*(..))")
public void businessService() {}
@Aspect public class AroundExample {
@Around("com.xyz.myapp.SystemArchitecture.businessService()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
// start stopwatch
Object retVal = pjp.proceed();
// stop stopwatch
return retVal; }
Demo
29

More Related Content

What's hot

Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session ManagementFahad Golra
 
Apache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 UpdateApache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 UpdatePhil Steitz
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)Fahad Golra
 
PloneNG: What's new in Plone 4.2, 4.3, and beyond
PloneNG: What's new in Plone 4.2, 4.3, and beyondPloneNG: What's new in Plone 4.2, 4.3, and beyond
PloneNG: What's new in Plone 4.2, 4.3, and beyondDavid Glick
 
Java EE 8 Web Frameworks: A Look at JSF vs MVC
Java EE 8 Web Frameworks: A Look at JSF vs MVCJava EE 8 Web Frameworks: A Look at JSF vs MVC
Java EE 8 Web Frameworks: A Look at JSF vs MVCJosh Juneau
 
Java Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCJava Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCIMC Institute
 
Java EE 6, Eclipse @ EclipseCon
Java EE 6, Eclipse @ EclipseConJava EE 6, Eclipse @ EclipseCon
Java EE 6, Eclipse @ EclipseConLudovic Champenois
 
Ejb 2.0
Ejb 2.0Ejb 2.0
Ejb 2.0sukace
 
Fun with EJB 3.1 and Open EJB
Fun with EJB 3.1 and Open EJBFun with EJB 3.1 and Open EJB
Fun with EJB 3.1 and Open EJBArun Gupta
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programmingKumar
 
Declarative Services Dependency Injection OSGi style
Declarative Services Dependency Injection OSGi styleDeclarative Services Dependency Injection OSGi style
Declarative Services Dependency Injection OSGi styleFelix Meschberger
 
深入淺出 MVC
深入淺出 MVC深入淺出 MVC
深入淺出 MVCJace Ju
 
SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016Alex Theedom
 

What's hot (20)

Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
Apache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 UpdateApache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 Update
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
 
PloneNG: What's new in Plone 4.2, 4.3, and beyond
PloneNG: What's new in Plone 4.2, 4.3, and beyondPloneNG: What's new in Plone 4.2, 4.3, and beyond
PloneNG: What's new in Plone 4.2, 4.3, and beyond
 
Java EE 8 Web Frameworks: A Look at JSF vs MVC
Java EE 8 Web Frameworks: A Look at JSF vs MVCJava EE 8 Web Frameworks: A Look at JSF vs MVC
Java EE 8 Web Frameworks: A Look at JSF vs MVC
 
Java Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCJava Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVC
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
 
Java EE 6, Eclipse @ EclipseCon
Java EE 6, Eclipse @ EclipseConJava EE 6, Eclipse @ EclipseCon
Java EE 6, Eclipse @ EclipseCon
 
Next stop: Spring 4
Next stop: Spring 4Next stop: Spring 4
Next stop: Spring 4
 
Ejb 2.0
Ejb 2.0Ejb 2.0
Ejb 2.0
 
Fun with EJB 3.1 and Open EJB
Fun with EJB 3.1 and Open EJBFun with EJB 3.1 and Open EJB
Fun with EJB 3.1 and Open EJB
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
 
Declarative Services Dependency Injection OSGi style
Declarative Services Dependency Injection OSGi styleDeclarative Services Dependency Injection OSGi style
Declarative Services Dependency Injection OSGi style
 
深入淺出 MVC
深入淺出 MVC深入淺出 MVC
深入淺出 MVC
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Spring WebApplication development
Spring WebApplication developmentSpring WebApplication development
Spring WebApplication development
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016
 

Similar to Spring introduction

CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287Ahmad Gohar
 
2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdfDeoDuaNaoHet
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAOAnushaNaidu
 
Spring training
Spring trainingSpring training
Spring trainingshah_d_p
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Hitesh-Java
 
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 Framework Presantation Part 1-Core
Spring Framework Presantation Part 1-CoreSpring Framework Presantation Part 1-Core
Spring Framework Presantation Part 1-CoreDonald Lika
 
Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introductionOndrej Mihályi
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questionsDhiraj Champawat
 
Spring training
Spring trainingSpring training
Spring trainingTechFerry
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
Enterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business LogicEnterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business LogicEmprovise
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204s4al_com
 
The future of enterprise dependency injection: Contexts & Dependency Injectio...
The future of enterprise dependency injection: Contexts & Dependency Injectio...The future of enterprise dependency injection: Contexts & Dependency Injectio...
The future of enterprise dependency injection: Contexts & Dependency Injectio...Paul Bakker
 

Similar to Spring introduction (20)

CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287
 
2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAO
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
 
Spring training
Spring trainingSpring training
Spring training
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
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 Framework Presantation Part 1-Core
Spring Framework Presantation Part 1-CoreSpring Framework Presantation Part 1-Core
Spring Framework Presantation Part 1-Core
 
Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introduction
 
Spring session
Spring sessionSpring session
Spring session
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
 
Spring training
Spring trainingSpring training
Spring training
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Enterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business LogicEnterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business Logic
 
Spring core
Spring coreSpring core
Spring core
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
Spring
SpringSpring
Spring
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204
 
The future of enterprise dependency injection: Contexts & Dependency Injectio...
The future of enterprise dependency injection: Contexts & Dependency Injectio...The future of enterprise dependency injection: Contexts & Dependency Injectio...
The future of enterprise dependency injection: Contexts & Dependency Injectio...
 
Spring framework
Spring frameworkSpring framework
Spring framework
 

Recently uploaded

What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 

Recently uploaded (20)

What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 

Spring introduction

  • 1. FPT APTECH COMPUTER EDUCATION HANOI Spring Framework
  • 2. 2
  • 4. 4
  • 5. Bean scopes • singleton (Default) Scopes a single bean definition to a single object instance per Spring IoC container. • prototype Scopes a single bean definition to any number of object instances. • request Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext. • session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware SpringApplicationContext. • global session Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext. • custom scope To integrate your custom scope(s) into the Spring container, you need to implement the org.springframework.beans.factory.config.Scope interface
  • 8. Constructor-based dependency injection • Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments public class SimpleMovieLister { // the SimpleMovieLister has a dependency on a MovieFinder private MovieFinder movieFinder; // a constructor so that the Spring container can 'inject' a MovieFinder public SimpleMovieLister(MovieFinder movieFinder) { this.movieFinder = movieFinder; } } <bean id=“simpleMovieLister ” class=“example. SimpleMovieLister ”> <constructor-arg name=“movieFinder”><ref bean=“movieFinder”/> </bean> <bean id=“movieFinder” class=“example. MovieFinder”>
  • 9. Setter-based dependency injection • Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argumentstatic factory method to instantiate your bean. public class SimpleMovieLister { // the SimpleMovieLister has a dependency on a MovieFinder private MovieFinder movieFinder; public SimpleMovieLister() { } // a setter method so that the Spring container can 'inject' a MovieFinder public setMovieFinder (MovieFinder movieFinder) { this.movieFinder = movieFinder; } } <bean id=“simpleMovieLister ” class=“example. SimpleMovieLister ”> <property name=“movieFinder”><ref bean=“movieFinder”/> </property> </bean> <bean id=“movieFinder” class=“example. MovieFinder”>
  • 10. Abstract Beans • Allows definition of part of a bean which can be reused many times in other bean definitions 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 <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>
  • 11. The singleton scope • The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made. That is, the bean is injected into another bean or you request it through a getBean() method call on the container. As a rule, use the prototype scope for all stateful beans and the singleton scope for stateless beans. • The following diagram illustrates the Spring prototype scope. A data access object (DAO) is not typically configured as a prototype, because a typical DAO does not hold any conversational state; it was just easier for this author to reuse the core of the singleton diagram. <bean id="accountService" class=“DefaultAccountService"/> <!-- the following is equivalent, though redundant (singleton scope is the default) --> <bean id="accountService" class=“DefaultAccountService" scope="singleton“/>
  • 12. The prototype scope • The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made. That is, the bean is injected into another bean or you request it through a getBean() method call on the container. As a rule, use the prototype scope for all stateful beans and the singleton scope for stateless beans. • The following diagram illustrates the Spring prototype scope. A data access object (DAO) is not typically configured as a prototype, because a typical DAO does not hold any conversational state; it was just easier for this author to reuse the core of the singleton diagram. <bean id="accountService" class=“DefaultAccountService" scope="prototype“/>
  • 13. Request, session, and global session scopes • Request scope The Spring container creates a new instance of the LoginAction bean by using the loginAction bean definition for each and every HTTP request. That is, the loginAction bean is scoped at the HTTP request level. You can change the internal state of the instance that is created as much as you want, because other instances created from the same loginAction bean definition will not see these changes in state; they are particular to an individual request. When the request completes processing, the bean that is scoped to the request is discarded. • Session scope The Spring container creates a new instance of the UserPreferences bean by using the userPreferences bean definition for the lifetime of a single HTTP Session. In other words, the userPreferences bean is effectively scoped at the HTTP Session level. As with request-scoped beans, you can change the internal state of the instance that is created as much as you want, knowing that other HTTP Session instances that are also using instances created from the same userPreferences bean definition do not see these changes in state, because they are particular to an individual HTTP Session. When the HTTP Session is eventually discarded, the bean that is scoped to that particular HTTP Session is also discarded. • Global session scope The global session scope is similar to the standard HTTP Session scope and applies only in the context of portlet-based web applications. The portlet specification defines the notion of a global Session that is shared among all portlets that make up a single portlet web application. Beans defined at the global session scope are scoped (or bound) to the lifetime of the global portlet Session. <bean id="loginAction" class="com.foo.LoginAction" scope="request"/> <bean id="userPreferences" class="com.foo.UserPreferences" scope="session“/> <bean id="userPreferences" class="com.foo.UserPreferences" scope="globalSession”/>
  • 14. The Spring IOC Container 14 BeanFactory
  • 15. Container Instantiation Instantiating a Spring IoC container is easy; • Resource resource = new FileSystemResource("beans.xml"); – BeanFactory factory = new XmlBeanFactory(resource); • ClassPathResource resource = new ClassPathResource("beans.xml"); – BeanFactory factory = new XmlBeanFactory(resource); • ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {"applicationContext.xml", "applicationContext- part2.xml"}); // of course, an ApplicationContext is just a BeanFactory – BeanFactory factory = (BeanFactory) context; 15
  • 18. We believe that Aspect-Oriented Programming (AOP) offers a better solution to many problems than do existing technologies such as EJB. The AOP Alliance aims to ensure interoperability between Java/J2EE AOP implementations to build a larger AOP community. AOP Alliance(http://aopalliance.sourceforge.net/)
  • 19. Proxy pattern DEAE / Session 9 19
  • 20. Decorator pattern DEAE / Session 9 20
  • 21. AOP Fundamentals • Aspect-oriented programming (AOP) provides for simplified application of cross-cutting concerns – Transaction management – Security – Logging – Auditing – Locking 21
  • 22. AOP concepts • Aspect: a modularization of a concern that cuts across multiple classes • Join point: a point during the execution of a program • Advice: action taken by an aspect at a particular join point • Pointcut: a predicate that matches join points • Introduction: declaring additional methods or fields on behalf of a type: • Target object: object being advised by one or more aspects • AOP proxy: an object created by the AOP framework in order to implement the aspect contracts • Weaving: linking aspects with other application types or objects to create an advised object 22
  • 23. Types of advice • Before advice • After returning advice • After throwing advice • After (finally) advice • Around advice DEAE / Session 9 23
  • 24. AOP Proxies • Spring AOP defaults to using standard J2SE dynamic proxies for AOP proxies • Spring AOP can also use CGLIB proxies DEAE / Session 9 24
  • 25. @AspectJ support • @AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations • Support configuration with XML DEAE / Session 9 25
  • 26. Declaring a pointcut • execution - for matching method execution join points, this is the primary pointcut designator you will use when working with Spring AOP • within - limits matching to join points within certain types (simply the execution of a method declared within a matching type when using Spring AOP) • this - limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type • target - limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type • args - limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types 26
  • 28. Declaring Pointcut & Advice • Declaring A Pointcut • Declaring advice <aop:config> <aop:advisor pointcut=“SystemArchitecture.businessService()" advice-ref="tx-advice"/> </aop:config> <tx:advice id="tx-advice"> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> Or @Pointcut("execution(* com.xyz.someapp.service.*.*(..))") public void businessService() {} @Aspect public class AroundExample { @Around("com.xyz.myapp.SystemArchitecture.businessService()") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { // start stopwatch Object retVal = pjp.proceed(); // stop stopwatch return retVal; }

Editor's Notes

  1. When you create a bean definition, you create a recipe for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, as with a class, you can create many object instances from a single recipe.You can control not only the various dependencies and configuration values that are to be plugged into an object that is created from a particular bean definition, but also the scope of the objects created from a particular bean definition. This approach is powerful and flexible in that you canchoose the scope of the objects you create through configuration instead of having to bake in the scope of an object at the Java class level. Beans can be defined to be deployed in one of a number of scopes: out of the box, the Spring Framework supports five scopes, three of which are available only if you use a web-aware ApplicationContext.
  2. http://static.springsource.org/spring/docs/2.5.3/reference/introduction.htmlGói core là phần cơ bản nhất của framework này và cung cấp các IoC và các tính năng Dependency Injection. Các khái niệm cơ bản ở đây là BeanFactory, cung cấp một implementation tinh xảo của mô hình Factory mà loại bỏ sự cần thiết của lập trình singletons và cho phép bạn cóthể tách các cấu hình và đặctảcủa dependencies với logic chương trình thực tế của bạn.Gói Contextxây dựng trên cơ sở vững chắc cung cấp bởi gói Core: nó cung cấp một cách để tiếp cận đối tượng theocáchcủamột framework phần nào gợi nhớ đếnJNDI-registry. Gói context kế thừa các tính năng của nó từ gói beans và thêm hỗ trợ cho quốc tế hóa (i18n), event-propagation, resource-loading, and the transparent creation of contexts by, for example, a servlet container.Gói DAO cung cấp một lớp JDBC-abstraction mà loại bỏ sự cần thiết phải làm tẻ nhạt lậptrìnhJDBC và phân tích cơ sở dữ liệu mã lỗi cụ thể củatừng nhà cung cấp. Ngoài ra, các gói JDBC cung cấp một cách để làm chương trình cũng như quản lý transaction, không chỉ cho các classes implementing các interfaces đặc biệt, nhưng đối với tất cả các POJO.Gói ORM cung cấp các lớp tíchhợpcho các object-relational mapping API phổbiến, bao gồm JPA, JDO, Hibernate, và iBatis. Sử dụng gói ORM bạn có thể sử dụng tất cả các O / R mappers kết hợp với tất cả các tính năng khác Spring offer, chẳng hạn như các tính năng quản lý giao dịch khai báo đơn giản đề cập trước đó.Gói AOP của Spring cung cấp một AOP Alliancetuânthủlập trình hướng khía cạnh cho phép bạn địnhnghĩa, ví dụ method-interceptors và pointcuts để tách mã thực hiện chức năng một cách hợp lý. Sử dụng chức năng source-level metadata bạn cũng có thể kết hợp tất cả các loại thông tin về hành vi vào mã của bạn, một cách tương tự như của NET attributes..Gói Web Spring cung cấp tính năng cơbảntích hợphướng web, chẳng hạn như chức năng upload nhiều file cùnglúc, việc khởi tạo các IoC container sử dụng servlet listeners và context ứng dụnghướng web. Khi sử dụng Spring cùng với WebWork hay Struts, đây là gói phần mềm để tích hợp vớichúng.Gói Spring MVCcung cấp một Model-View-Controller (MVC) thực hiện cho các ứng dụng web. Khung MVC mùa xuân không chỉ là một thực thi của mô hình cũ, nó cung cấp một tách biệtrõràng giữa các mã domain model và web forms, và cho phép bạn sử dụng tất cả các tính năng khác của Spring Framework. 
  3. http://static.springsource.org/spring/docs/3.2.0.RELEASE/spring-framework-reference/html/overview.html
  4. constructor-based dependency injection is realized by invoking a constructor with a number of arguments, each representing a collaborator or property. Although Spring generally advocates usage of setter-based dependency injection as much as possible, it does fully support the constructor-based approach as well, since you may wish to use it with pre-existing beans which provide only multi-argument constructors, and no setters. Additionally, for simpler beans, some people prefer the constructor approach as a means of ensuring beans can not be constructed in an invalid state.
  5. setter-based dependency injection is realized by calling setters on your beans after invoking a no-argument constructor to instantiate your bean. Beans defined in the BeanFactory that use setter-based dependency injection are true JavaBeans. Spring generally advocates usage of setter-based dependency injection, since a large number of constructor arguments can get unwieldy, especially when some properties are optional.
  6. Spring&apos;s concept of a singleton bean differs from the Singleton pattern as defined in the Gang of Four (GoF) patterns book. The GoF Singleton hard-codes the scope of an object such that one and only one instance of a particular class is created per ClassLoader. The scope of the Spring singleton is best described as per container and per bean. This means that if you define one bean for a particular class in a single Spring container, then the Spring container creates one and only one instance of the class defined by that bean definition. The singleton scope is the default scope in Spring. To define a bean as a singleton in XML.
  7. In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance. Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called. The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding. To get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-processor, which holds a reference to beans that need to be cleaned up.
  8. Note: The request, session, and global session scopes are only available if you use a web-aware Spring ApplicationContext implementation (such as XmlWebApplicationContext). If you use these scopes with regular Spring IoC containers such as the ClassPathXmlApplicationContext, you get an IllegalStateException complaining about an unknown bean scope.Initial web configurationo support the scoping of beans at the request, session, and global session levels (web-scoped beans), some minor initial configuration is required before you define your beans. (This initial setup is not required for the standard scopes, singleton and prototype.)How you accomplish this initial setup depends on your particular Servlet environment..If you access scoped beans within Spring Web MVC, in effect, within a request that is processed by the Spring DispatcherServlet, orDispatcherPortlet, then no special setup is necessary: DispatcherServlet and DispatcherPortlet already expose all relevant state.If you use a Servlet 2.4+ web container, with requests processed outside of Spring&apos;s DispatcherServlet (for example, when using JSF or Struts), you need to add the following javax.servlet.ServletRequestListener to the declarations in your web applications web.xml file:&lt;web-app&gt; ... &lt;listener&gt; &lt;listener-class&gt; org.springframework.web.context.request.RequestContextListener &lt;/listener-class&gt; &lt;/listener&gt; ... &lt;/web-app
  9. The org.springframework.beans.factory.BeanFactory is the actual representation of the Spring IoC container that is responsible for containing and otherwise managing the aforementioned beans.The BeanFactory interface is the central IoC container interface in Spring. Its responsibilities include instantiating or sourcing application objects, configuring such objects, and assembling the dependencies between these objects.There are a number of implementations of the BeanFactory interface that come supplied straight out-of-the-box with Spring. The most commonly used BeanFactory implementation is the XmlBeanFactory class. This implementation allows you to express the objects that compose your application, and interdependencies between such objects, in terms of XML. The XmlBeanFactory takes this XML configuration and uses it to create a fully configured system.
  10. http://static.springsource.org/spring/docs/3.2.0.RELEASE/spring-framework-reference/html/aop.html
  11. Aspect: a modularization of a concern that cuts across multiple classes. Transaction management is a good example of a crosscutting concern in enterprise Java applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style). Join point: a point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution. Advice: action taken by an aspect at a particular join point. Different types of advice include &quot;around,&quot; &quot;before&quot; and &quot;after&quot; advice. (Advice types are discussed below.) Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors around the join point.Pointcut: a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJpointcut expression language by default. Introduction: declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any advised object. For example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching. (An introduction is known as an inter-type declaration in the AspectJ community.) Target object: object being advised by one or more aspects. Also referred to as the advised object. Since Spring AOP is implemented using runtime proxies, this object will always be a proxied object. AOP proxy: an object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy. Weaving: linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.
  12. Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.After throwing advice: Advice to be executed if a method exits by throwing an exception.After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.
  13. http://static.springsource.org/spring/docs/2.5.5/reference/aop.html#aop-understanding-aop-proxieshttp://www.roseindia.net/tutorial/spring/spring3/aop/index.html
  14. Xemthêmtại: http://static.springsource.org/spring/docs/3.0.x/reference/aop.html#aop-pointcuts-examples
  15. Execution Pointcut Spring AOP users are likely to use the execution pointcut designator the most often. The format of an execution expression is:execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?) All parts except the returning type pattern (ret-type-pattern in the snippet above), name pattern, and parameters pattern are optional. The returning type pattern determines what the return type of the method must be in order for a join point to be matched. Most frequently you will use * as the returning type pattern, which matches any return type. A fully-qualified type name will match only when the method returns the given type. The name pattern matches the method name. You can use the * wildcard as all or part of a name pattern. The parameters pattern is slightly more complex: ()matches a method that takes no parameters, whereas (..) matches any number of parameters (zero or more). The pattern (*) matches a method taking one parameter of any type, (*,String) matches a method taking two parameters, the first can be of any type, the second must be a String.Around Advice Around advice runs &quot;around&quot; a matched method execution. It has the opportunity to do work both before and after the method executes, and to determine when, how, and even if, the method actually gets to execute at all. Around advice is often used if you need to share state before and after a method execution in a thread-safe manner (starting and stopping a timer for example). Always use the least powerful form of advice that meets your requirements (i.e. don&apos;t use around advice if simple before advice would do). Around advice is declared using the @Around annotation. The first parameter of the advice method must be of type ProceedingJoinPoint. Within the body of the advice, calling proceed() on the ProceedingJoinPoint causes the underlying method to execute. The proceed method may also be called passing in an Object[] - the values in the array will be used as the arguments to the method execution when it proceeds. The behavior of proceed when called with an Object[] is a little different than the behavior of proceed for around advice compiled by the AspectJ compiler. For around advice written using the traditional AspectJ language, the number of arguments passed to proceed must match the number of arguments passed to the around advice (not the number of arguments taken by the underlying join point), and the value passed to proceed in a given argument position supplants the original value at the join point for the entity the value was bound to (Don&apos;t worry if this doesn&apos;t make sense right now!). The approach taken by Spring is simpler and a better match to its proxy-based, execution only semantics. You only need to be aware of this difference if you are compiling @AspectJ aspects written for Spring and using proceed with arguments with the AspectJ compiler and weaver. There is a way to write such aspects that is 100% compatible across both Spring AOP and AspectJ, and this is discussed in the following section on advice parameters. The value returned by the around advice will be the return value seen by the caller of the method. A simple caching aspect for example could return a value from a cache if it has one, and invoke proceed() if it does not. Note that proceed may be invoked once, many times, or not at all within the body of the around advice, all of these are quite legal.