Date post: | 04-Apr-2018 |
Category: |
Documents |
Upload: | prashant-shirsath |
View: | 219 times |
Download: | 0 times |
of 57
7/31/2019 08 Spring Aop2
1/57
2008 coreservlets.com
Part 2
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/spring.html
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
2008 coreservlets.com
For live Spring & Hibernate training, seecourses a p: courses.coreserv e s.com .Taught by the experts that brought you this tutorial.
,can be held on-site at your organization.
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
ourses eve ope an aug y ar y a Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom mix of topics
Courses developed and taught by coreservlets.com experts (edited by Marty) Spring, Hibernate/JPA, EJB3, Ruby/Rails
Contact [email protected] for details
7/31/2019 08 Spring Aop2
2/57
Topics in This Section
Implementing aspect behavior
AspectJ APIs and annotations
Spring AOP application
Java EE trainin : htt ://courses.coreservlets.com4
2008 coreservlets.com
Aspect Behavior
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
7/31/2019 08 Spring Aop2
3/57
Aspect Behavior
AdviceBehavior to be applied to a set of program execution
points - ,
interest, e.g. transaction management. Advisor beans areapplied to pointcuts (a set of join points)
Spring advisor bean Implementation
Integration (one of the following)
Special interfaces org.aopalliance.aop.Advice
Java EE trainin : htt ://courses.coreservlets.com
Methods annotated with AspectJ annotations and definedwith AspectJ parameters types
6
Advice Types
Before on-critical advisor bean type
Called before method execution
Non-critical advisor bean type
Called after normal method execution After throwing
Non-critical advisor bean type
Around Critical advisor bean t e
Java EE trainin : htt ://courses.coreservlets.com
Wraps method execution
7
7/31/2019 08 Spring Aop2
4/57
2008 coreservlets.com
Before Advice
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Before Advice
Interface org.springframework.aop.MethodBeforeAdvice
Execution pointBefore method execution
TypeDoes not invoke method
Non-critical unless an error is thrown
Java EE trainin : htt ://courses.coreservlets.com9
7/31/2019 08 Spring Aop2
5/57
Before Advice Guidelines
UsesInput validation
Auditing/logging
Exception typeChecked exceptions must be coordinated with the
error s gna ure o e a v se ean Out-of-scope errors are re-thrown as
java.lang.reflect.UndeclaredThrowableException
RuntimeException types may be used without
precaution
Java EE trainin : htt ://courses.coreservlets.com10
Before Advice Process
Create new advice class Implement
org.springframework.aop.MethodBeforeAdvice
before(method:Method,
arguments:Object[],target:O ect :vo
throws Throwable
Re ister advice as a S rin bean
Reference from aspect
Java EE trainin : htt ://courses.coreservlets.com
Associate with a pointcut
Integrate with Spring domain beans11
7/31/2019 08 Spring Aop2
6/57
Create Before Advice Class
import java.lang.reflect.Method;
im ort or .s rin framework.ao .MethodBeforeAdvice
public class BeforeLoggingAdviceimplements MethodBeforeAdvice {
public void before(Method method,Object[] args,
Logger.getLogger(target.getClass()).debug(target.getClass().getSimpleName()
+ "#" + method.toGenericString()+ ". args=" + Arrays.toString(args));
Java EE trainin : htt ://courses.coreservlets.com
}
12
Register Before Advice Bean
Java EE trainin : htt ://courses.coreservlets.com13
7/31/2019 08 Spring Aop2
7/57
Reference From Aspect
reference
Java EE trainin : htt ://courses.coreservlets.com
14
Domain Beans
classpath:/coreservletsContext.xml
-
" " " "
Java EE trainin : htt ://courses.coreservlets.com
7/31/2019 08 Spring Aop2
8/57
Integrate Advice
import org.springframework.context.support.*;
public class Main {
public static void main(String[]args) {
BeanFactory beanFactory =new ClassPathXmlApplicationContext("/coreservletsContext.xml",
" "....
}}
Java EE trainin : htt ://courses.coreservlets.com
Access and Use Beansimport org.springframework.context.support.*;
public class Main {
public static void main(String[]args) {BeanFactory beanFactory =
new ClassPathXmlApplicationContext(new String[]{"/coreservletsContext.xml"," ".
CustomerQuery query =
(CustomerQuery) beanFactory.getBean("customerQuery");Customer customer = query.getCustomerByName("Java Joe");
}
}Standard output
Java EE trainin : htt ://courses.coreservlets.com
MockCustomerQuery#public abstract coreservlets.Customercoreservlets.CustomerQuery.getCustomerByName(java.lang.String). args=[Java Joe]
7/31/2019 08 Spring Aop2
9/57
2008 coreservlets.com
er e urn ng
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
After Returning Advice
Interface org.springframework.aop.AfterReturningAdvice
Execution point After normal method execution and exit
Type
Does not invoke method on-critical unless an error is thrown
Exception type
signature of the advised bean Out-of-scope errors are re-thrown as
Java EE trainin : htt ://courses.coreservlets.com
ava. ang.re ec . n ec are rowa e xcep on
RuntimeException types may be used without precaution
19
7/31/2019 08 Spring Aop2
10/57
After Returning Advice
Create new advice class Implement
org.springframework.aop.AfterReturningAdvice Fulfill
afterReturning(returnValue:Object,
method:Method,
arguments:Object[],
target:Object):voidthrows Throwable
Reference from aspect
Java EE trainin : htt ://courses.coreservlets.com
Associate with a pointcut
Integrate with Spring domain beans20
After Returning Advice Classimport java.lang.reflect.Method;im ort or .s rin framework.ao . AfterReturnin Advice
public class BeforeLoggingAdviceimplements AfterReturningAdvice {
public void afterReturning(Object returnValue,Method method,
,Object target) throws Throwable {
Logger.getLogger(target.getClass()).debug("exit=return[" + returnValue + "]");
}
Java EE trainin : htt ://courses.coreservlets.com21
7/31/2019 08 Spring Aop2
11/57
Register After Returning
Java EE trainin : htt ://courses.coreservlets.com22
Reference From Aspect
reference
Java EE trainin : htt ://courses.coreservlets.com
23
7/31/2019 08 Spring Aop2
12/57
Domain Beans
classpath:/coreservletsContext.xml
-
" " " "
Java EE trainin : htt ://courses.coreservlets.com
Integrate Adviceimport org.springframework.context.support.*;
public class Main {public static void main(String[]args) {
BeanFactory beanFactory =
new ClassPathXmlApplicationContext("/coreservletsContext.xml"," ".
...
}}
Java EE trainin : htt ://courses.coreservlets.com
7/31/2019 08 Spring Aop2
13/57
Access and Use Beans
import org.springframework.context.support.*;
public class Main {
public static void main(String[]args) {BeanFactory beanFactory =new ClassPathXmlApplicationContext(new String[]{"/coreservletsContext.xml",
" ".CustomerQuery query =(CustomerQuery) beanFactory.getBean("customerQuery");Customer customer = query.getCustomerByName("Java Joe");
}}
Java EE trainin : htt ://courses.coreservlets.com
Standard output
exit=return[Customer id=jjoe, name=Java Joe]
2008 coreservlets.com
Throws Advice
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
7/31/2019 08 Spring Aop2
14/57
Throws Advice
Interface . . .
Interface is an empty marker with virtualized callbacks
Implementation
afterThrowing(throwable:Throwable):void
afterThrowing(method:Method,
args:Object[],
target:Object,
throwable:Throwable);
Execution point After method exit on error
Does not intercept errors originating from preceding advisors
T e
Java EE trainin : htt ://courses.coreservlets.com
Does not invoke method
Non-critical unless an error is thrown28
Throws Advice Guidelines
Uses Adapting API error behavior
Error conformance to a domain type
Exception may be overridden by re-throwing an alternate error
Exception type Checked exceptions must be coordinated with the error
signature of the advised bean Out-of-sco e errors are re-thrown as
java.lang.reflect.UndeclaredThrowableException
RuntimeException types may be used without precaution
Java EE trainin : htt ://courses.coreservlets.com29
7/31/2019 08 Spring Aop2
15/57
Throws Advice Guidelines
Overloading by type Advice bean may overload methods to support varying error
types The most recise advisin method is selected er the
Throwable type
Overloading by detail pproac s am guous
Full method implementation is selected
Java EE trainin : htt ://courses.coreservlets.com30
Throws Advice Process
Create new advice class Implement
org.springframework.aop.ThrowsAdvice
Define one or more interceptor methods afterThrowing(throwable:Throwable):void
afterThrowing(method:Method,
args:Object[],target:Object,
throwable:Throwable);
Reference from aspect
Java EE trainin : htt ://courses.coreservlets.com
Associate with a pointcut
Integrate with Spring domain beans31
7/31/2019 08 Spring Aop2
16/57
Throws Advice Class
import java.lang.reflect.Method;
im ort or .s rin framework.ao .ThrowsAdvicepublic class ThrowsLoggingAdvice implements ThrowsAdvice {
public void afterThrowing(Method method, Object[] arguments, Object target, IllegalArgumentException ex) throws Throwable {
Logger.getLogger(target.getClass()).debug(
" "}public void afterThrowing(Method method
, Object[] arguments
, Object target, IllegalStateException ex) throws Throwable {
Logger.getLogger(target.getClass()).debug(
Java EE trainin : htt ://courses.coreservlets.com
a er row ng: ega a e xcep on ;}
}32
Register Throws Advice Bean
Java EE trainin : htt ://courses.coreservlets.com33
7/31/2019 08 Spring Aop2
17/57
Reference From Aspect
Advisor
reference
Java EE trainin : htt ://courses.coreservlets.com
34
Mock Domain Classpublic class ErrorThrowingMockCustomerQueryim lements Customer uer
private Class
7/31/2019 08 Spring Aop2
18/57
Domain Beans
classpath:/coreservletsContext.xml
-value="java.lang.IllegalArgumentException" />
Java EE trainin : htt ://courses.coreservlets.com
Integrate Adviceimport org.springframework.context.support.*;
public class Main {public static void main(String[]args) {
BeanFactory beanFactory =
new ClassPathXmlApplicationContext("/coreservletsContext.xml"," ".
...
}}
Java EE trainin : htt ://courses.coreservlets.com
7/31/2019 08 Spring Aop2
19/57
Access and Use Beans
import org.springframework.context.support.*;
ublic class Mainpublic static void main(String[]args) {
BeanFactory beanFactory =new ClassPathXmlApplicationContext(new String[]{"/coreservletsContext.xml","/coreservletsAopContext.xml"});
CustomerQuery query =
" ".Customer customer = query.getCustomerByName("Java Joe");
}}
Standard output
afterThrowing: IllegalArgumentException
Java EE trainin : htt ://courses.coreservlets.com
Except on n t rea "ma n"java.lang.IllegalArgumentException
2008 coreservlets.com
Around Advice
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
7/31/2019 08 Spring Aop2
20/57
Around Advice
Interface org.springframework.aop.MethodInterceptor
Execution pointWraps method invocation
Wraps other advisors
index values
Perceives return types and errors from target beans and
Type
Java EE trainin : htt ://courses.coreservlets.com
Critical path
40
Around Advice Guidelines
Uses Transaction management
Full templating cases
Exception may be overridden by re-throwing an alternate error
Exceptions may also be suppressed xcep on ype
Checked exceptions must be coordinated with the errorsi nature of the advised bean
Out-of-scope errors are re-thrown as
java.lang.reflect.UndeclaredThrowableException
Java EE trainin : htt ://courses.coreservlets.com
41
7/31/2019 08 Spring Aop2
21/57
Around Advice Process
Create new advice class Implement
org.springframework.aop.MethodInterceptor Fulfill
invoke(handle:MethodInvocation):Object
throws Throwable
Invoke tar et return handle.proceed();
Register advice as a Spring bean ean
Reference from aspect Associate with a ointcut
Java EE trainin : htt ://courses.coreservlets.com
Integrate with Spring domain beans
42
Around Advice Classimport org.aopalliance.intercept.MethodInterceptor;
public class NamedAroundAdvice
implements MethodInterceptor {
private String name;
public NamedAroundAdvice(String name){this.name = name;
}
public Object invoke(MethodInvocation invocation)throws Throwable {
Java EE trainin : htt ://courses.coreservlets.com
...}
}43
7/31/2019 08 Spring Aop2
22/57
Around Advice Class Continued
...
throws Throwable {
try{log.debug("before: " + this.name);Object returnValue = invocation.proceed();log.debug("after return: " + this.name);return returnValue;
}catch(Throwable t){log.debug("after throws: " + this.name);t row t;
}
finally{" "
Java EE trainin : htt ://courses.coreservlets.com
. .}
}...44
Register Around Advice Bean
< ean>
Java EE trainin : htt ://courses.coreservlets.com45
7/31/2019 08 Spring Aop2
23/57
Reference From Aspect
Advisor
reference
- =" "
Java EE trainin : htt ://courses.coreservlets.com
pointcut-ref="customerQueryPointcut" />
46
Domain Beans
classpath:/coreservletsContext.xml
-
" " " "
Java EE trainin : htt ://courses.coreservlets.com
7/31/2019 08 Spring Aop2
24/57
Integrate Advice
import org.springframework.context.support.*;
public class Main {
public static void main(String[]args) {
BeanFactory beanFactory =new ClassPathXmlApplicationContext("/coreservletsContext.xml",
" "....
}}
Java EE trainin : htt ://courses.coreservlets.com
Access and Use Beansimport org.springframework.context.support.*;ublic class Main
public static void main(String[]args) {BeanFactory beanFactory =new ClassPathXmlApplicationContext(new String[]{"/coreservletsContext.xml",
"/coreservletsAopContext.xml"});CustomerQuery query =
" ".Customer customer = query.getCustomerByName("Java Joe");
}}
Standard output
before: namedAroundAdvice
Java EE trainin : htt ://courses.coreservlets.com
after return: namedAroundAdviceafter finally: namedAroundAdvice
7/31/2019 08 Spring Aop2
25/57
2008 coreservlets.com
Advice Ordering
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Around Advice
Controls Aspect execution order among similar advice types
Configuration v
Java EE trainin : htt ://courses.coreservlets.com51
7/31/2019 08 Spring Aop2
26/57
Around Advice Class
public class NamedAroundAdvice implements MethodInterceptor {
...public Object invoke(MethodInvocation inv) throws Throwable
{ try{og. e ug " e ore: " + t s.name ;Object returnValue = inv.proceed();log.debug("after return: " + this.name);
}catch(Throwable t){log.debug("after throws: " + this.name);
throw t;}
finally{" "
Java EE trainin : htt ://courses.coreservlets.com
. .}
}}52
Configure Aspect Order
Java EE trainin : htt ://courses.coreservlets.com
53
7/31/2019 08 Spring Aop2
27/57
Access and Use Beans
import org.springframework.context.support.*;
ublic class Mainpublic static void main(String[]args) {
BeanFactory beanFactory =new ClassPathXmlApplicationContext(new String[]{"/coreservletsContext.xml","/coreservletsAopContext.xml"});
CustomerQuery query =
" ".Customer customer = query.getCustomerByName("Java Joe");
}} Standard output
before: advisor-0before: advisor-1after return: advisor-1
Java EE trainin : htt ://courses.coreservlets.com
after finally: advisor-1after return: advisor-0after finally: advisor-0
2008 coreservlets.com
AspectJ Pointcuts
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
7/31/2019 08 Spring Aop2
28/57
AspectJ Pointcuts Introduction
DesignReuses class and method namespace for enumerating
pointcut definitions u s u e or pr ng sc ema suppor
Pointcut definitions are aggregated into an annotated
class
Classes containing pointcut elements are marked
using the @Aspect annotation
Java EE trainin : htt ://courses.coreservlets.com56
AspectJ Pointcuts Introduction
Pointcut element An annotated method, @Pointcut, represents a single pointcut
definition
The class and method combination is the uni ue ointcutidentifier .()
Pointcut methods are ublic instance methods acce t noarguments, and specify avoid return type
Pointcut expression T e po ntcut e n t on s expresse as @Pointcut annotat on
content
Java EE trainin : htt ://courses.coreservlets.com57
7/31/2019 08 Spring Aop2
29/57
AspectJ Pointcuts Process
Create new pointcut definitions class Annotate class with @Aspect
Define pointcuts
Annotate method with @Pointcut
Specify pointcut definition as @Pointcut annotation content
rea e a v ce c ass Implement an AOP Alliance interface
org.aopalliance.aop.Advice
Register advice as a Spring bean
Java EE trainin : htt ://courses.coreservlets.com
e erence a v ce an po n cu rom aspec
Integrate with Spring domain beans58
Select Join Pointspublic interface CustomerQuery {
public Customer getCustomerByName(String name);
}
public interface CustomerReport {
public String getReport(String customerName);
}
Java EE trainin : htt ://courses.coreservlets.com59
7/31/2019 08 Spring Aop2
30/57
Select Join Points Continued
public class MockCustomerQuery implements CustomerQuery {
private List customers;
public MockCustomerQuery(List customers) {this.customers = customers != null? customers : new ArrayList();
}
public Customer getCustomerByName(String name) {for(Customer c : customers){if(c.getName().equals(name)){
return c;}
}
Java EE trainin : htt ://courses.coreservlets.com
return nu ;
}}
60
Select Join Points Continuedpublic class MockCustomerReport implements CustomerReport{
private CustomerQuery query;
public MockCustomerReport(CustomerQuery query){
this.query = query;
public String getReport(String customerName){
Customer customer =
query.getCustomerByName(customerName);return customer != null
Java EE trainin : htt ://courses.coreservlets.com
? customer.toString() : null;
}61
7/31/2019 08 Spring Aop2
31/57
Create Pointcut Definitions
import org.aspectj.lang.annotation.Aspect;
im ort or .as ect .lan .annotation.Pointcut
@Aspectpublic class CoreservletsPointcuts {
}
Java EE trainin : htt ://courses.coreservlets.com62
Define Pointcutsimport org.aspectj.lang.annotation.Aspect;im ort or .as ect .lan .annotation.Pointcut
@Aspectpublic class CoreservletsPointcuts {
@Pointcut("target(coreservlets.CustomerQuery)")public void queryLayer(){}
@Pointcut("target(coreservlets.CustomerReport)")
public void reportLayer(){}
}
Java EE trainin : htt ://courses.coreservlets.com63
7/31/2019 08 Spring Aop2
32/57
Create Advice Class
public class LoggingMethodAdvice
im lements MethodInterce torpublic Object invoke(MethodInvocation i) throws Throwable {
String buf = ...;try{Object returnValue = i.proceed();buf += "\n - ex return : " + returnValue;return returnValue;
catch(Throwable t){buf += "\n - ex error : "
+ t.getClass().getName() + " - " + t.getMessage();
throw t;}
finally{
Java EE trainin : htt ://courses.coreservlets.com
ogger.ge ogger .ge s .ge ass . e ug u ;}
}64
Register Advice Bean
< eans>
Java EE trainin : htt ://courses.coreservlets.com65
7/31/2019 08 Spring Aop2
33/57
Define Aspect
Java EE trainin : htt ://courses.coreservlets.com
66
Domain Beans
classpath:/coreservletsContext.xml< eans>
- =" "
=" " =" "
Java EE trainin : htt ://courses.coreservlets.com
7/31/2019 08 Spring Aop2
34/57
Access and Use Beans
import org.springframework.context.support.*;
ublic class Mainpublic static void main(String[]args) {
BeanFactory beanFactory = ...;CustomerReport reportService =(CustomerReport) beanFactory.getBean("customerReport");reportService.getReport("Java Joe");
}Standard output
LoggingMethodAdvice- target : coreservlets.MockCustomerQuery- method : getCustomerByName[class java.lang.String]-- ex return : Customer id=jjoe, name=Java Joe
LoggingMethodAdvice- target : coreservlets.MockCustomerReport
Java EE trainin : htt ://courses.coreservlets.com
- method : getReport[class java.lang.String]- arg values: Java Joe- ex return : Customer id=jjoe, name=Java Joe
2008 coreservlets.com
AspectJ Advice
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
7/31/2019 08 Spring Aop2
35/57
AspectJ Advice Introduction
Advice class o special interfaces
Annotated with @Aspect
Annotated with advice classifier @Before
A terReturn ng
@AfterThrowing
@Around
ccess o JoinPoint, ProceedingJoinPoint, orJoinPoint.StaticPart
See org.aspectj.lang.*
Java EE trainin : htt ://courses.coreservlets.com
n y aroun a v ce s cr t ca to target execut on
70
AspectJ Advice Introduction
Annotation contentSpecifies pointcut definition as a pointcut expression
e.g., @Around("Pointcuts.layer()")
. ., = . ,
argNames="")
Annotation ro ert ar NamesSupplies advice method parameter names to pointcut
ConfigurationReplaces Spring AOP XML schema
Annotated advisor is a Spring bean
Java EE trainin : htt ://courses.coreservlets.com
Scanne y a ean post processor Requires element
71
7/31/2019 08 Spring Aop2
36/57
AspectJ Pointcuts Process
Create new pointcut definitions class Annotate class with @Aspect
Define pointcuts
Annotate method with @Pointcut
Specify pointcut definition as @Pointcut annotation content
Create advice class Annotate class with @Aspect
annotation
e.g. @Around
Java EE trainin : htt ://courses.coreservlets.com
pec y po n cu re erence as a v ce ype anno a on con en e.g. @Around("Pointcuts.layer()")
72
AspectJ Pointcuts Process
Skip
Register advice as a Spring bean
Bean annotations alread contains advice t e and ointcutreference
Indirectly references aspects and pointcuts
can spec anno a ons Add post processor instruction to bean definitions
Integrate with Spring domain beans
Java EE trainin : htt ://courses.coreservlets.com73
7/31/2019 08 Spring Aop2
37/57
Select Join Points
public interface CustomerQuery {
public Customer getCustomerByName(String name);
}
public interface CustomerReport {
public String getReport(String customerName);
}
Java EE trainin : htt ://courses.coreservlets.com74
Select Join Points Continuedpublic class MockCustomerQuery implements CustomerQuery {
private List customers;
public MockCustomerQuery(List customers) {this.customers = customers != null
? customers : new ArrayList();}
public Customer getCustomerByName(String name) {for(Customer c : customers){if(c.getName().equals(name)){return c;
}
}
Java EE trainin : htt ://courses.coreservlets.com
return nu ;}
}75
7/31/2019 08 Spring Aop2
38/57
Select Join Points Continued
public class MockCustomerReport implements CustomerReport{
private CustomerQuery query;
public MockCustomerReport(CustomerQuery query){
this.query = query;
public String getReport(String customerName){
Customer customer =
query.getCustomerByName(customerName);
return customer != null
Java EE trainin : htt ://courses.coreservlets.com
? customer.toString() : null;
}76
Define Pointcutsimport org.aspectj.lang.annotation.Aspect;im ort or .as ect .lan .annotation.Pointcut
@Aspectpublic class CoreservletsPointcuts {
@Pointcut("target(coreservlets.CustomerQuery)")public void queryLayer(){}
@Pointcut("target(coreservlets.CustomerReport)")
public void reportLayer(){}
}
Java EE trainin : htt ://courses.coreservlets.com77
7/31/2019 08 Spring Aop2
39/57
Create Advice Class
import org.apache.log4j.Logger;
im ort or .as ect .lan .Proceedin JoinPointimport org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
@Aspectpublic class LoggingAroundAdvice {
Java EE trainin : htt ://courses.coreservlets.com78
Create Advice Class@Aspectublic class Lo in AroundAdvice
@Around("coreservlets.CoreservletsPointcuts.queryLayer()"+ "|| coreservlets.CoreservletsPointcuts.reportLayer()")
public Object log(ProceedingJoinPoint jp)throws Throwable {Logger log = Logger.getLogger(jp.getTarget().getClass());
try{log.debug("before");
" " " ". . .Object returnValue = jp.proceed();
log.debug("after return");return returnValue;
}
catch(Throwable t){log.debug("after throws");
Java EE trainin : htt ://courses.coreservlets.com
row ;}
}79
7/31/2019 08 Spring Aop2
40/57
Register Advice Bean
< eans>
Java EE trainin : htt ://courses.coreservlets.com80
Register Bean Postprocessor
Java EE trainin : htt ://courses.coreservlets.com81
7/31/2019 08 Spring Aop2
41/57
Domain Beans
classpath:/coreservletsContext.xml- =" "
=" " =" "
Java EE trainin : htt ://courses.coreservlets.com
Access and Use Beansimport org.springframework.context.support.*;ublic class Main
public static void main(String[]args) {BeanFactory beanFactory = ...;CustomerReport reportService =(CustomerReport) beanFactory.getBean("customerReport");
reportService.getReport("Java Joe");}
Standard output
.coreservlets.MockCustomerReport #getReport()coreservlets.MockCustomerQuery before
Java EE trainin : htt ://courses.coreservlets.com
coreservlets.MockCustomerQuery after returncoreservlets.MockCustomerReport after return
7/31/2019 08 Spring Aop2
42/57
2008 coreservlets.com
S rin AOP
XML SchemaCustomized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
AspectJ Advice with Spring
Advice class o special interfaces
No annotations
Uses AspectJ API JoinPoint, ProceedingJoinPoint, or
JoinPoint.StaticPart
. . .
Only around advice is critical to target execution
Pointcut Defined by Spring AOP XML Schema
Java EE trainin : htt ://courses.coreservlets.com
Defined by Spring AOP XML Schema
85
7/31/2019 08 Spring Aop2
43/57
Process
Create advice class Optionally specify a join point parameter
Required for around advice typeS ecif return t e for around advice t e
Register advice bean
e ne po n cu
Declare pointcut ID and expression
Define aspect
Java EE trainin : htt ://courses.coreservlets.com
Reference advisor bean
86
Create Advice Classimport org.apache.log4j.Logger;im ort or .as ect .lan .Proceedin JoinPoint
public class LoggingAroundAdvice {public Object log(ProceedingJoinPoint jp)throws Throwable {
Logger log = Logger.getLogger(jp.getTarget().getClass());try{
log.debug("before");log.debug("#" + jp.getSignature().getName() + "()");
.log.debug("after return");
return returnValue;}catch(Throwable t){
log.debug("after throws");throw t;
Java EE trainin : htt ://courses.coreservlets.com
}
}87
7/31/2019 08 Spring Aop2
44/57
Register Advice Bean
< eans>
Java EE trainin : htt ://courses.coreservlets.com88
Define Pointcut
Java EE trainin : htt ://courses.coreservlets.com89
7/31/2019 08 Spring Aop2
45/57
Define Pointcut
- =" " =" "
Java EE trainin : htt ://courses.coreservlets.com
90
Domain Beans
classpath:/coreservletsContext.xml< eans>
- =" "
=" " =" "
Java EE trainin : htt ://courses.coreservlets.com
7/31/2019 08 Spring Aop2
46/57
Access and Use Beans
import org.springframework.context.support.*;
ublic class Mainpublic static void main(String[]args) {
BeanFactory beanFactory = ...;CustomerReport reportService =(CustomerReport) beanFactory.getBean("customerReport");reportService.getReport("Java Joe");
}
Standard output
.coreservlets.MockCustomerReport #getReport()
coreservlets.MockCustomerQuery before
Java EE trainin : htt ://courses.coreservlets.com
coreservlets.MockCustomerQuery after returncoreservlets.MockCustomerReport after return
2008 coreservlets.com
pr ng
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
7/31/2019 08 Spring Aop2
47/57
JDBC Transaction Management
ApplicationTransaction management over DAO persistence methods
Elements ata ource
Provides java.sql.Connection access/factory API
Integrates with RDBMS
DAO beans Identifies candidate transaction boundaries
Implements JDBC transaction management algorithms;
e.g. JTA
Java EE trainin : htt ://courses.coreservlets.com94
JDBC Transaction Management
Spring AOPAdvice
Abstracts transaction management services as a SpringAOP bean advisor
Pointcut Identifies persistence methods exposed by DAO beans
spec Associates transaction management bean advisor with a
pointcut
Java EE trainin : htt ://courses.coreservlets.com95
7/31/2019 08 Spring Aop2
48/57
Process
Develop persistence library .
coreservlets.CustomerBatchPersistence
coreservlets.SpringJdbcCustomerBatchPersistence
spring-core.jar, spring-context.jar, spring-beans.jar, spring-aop.jar,
aopalliance.jar, aspectjweaver.jar, cglib.jar, commons-logging.jar
e.g., classpath:/coreservletsPersistenceContext.xml
Register persistence beans " ". .,
class="coreservlets.CustomerBatchPersistence"/>
Inject dependencies
Java EE trainin : htt ://courses.coreservlets.com
. .,
Process
Create advice euse a v ce mp emen a on rom spr ng- x
spring-tx advice delegates transaction manager algorithms to aPlatformTransactionManager service
Re ister a PlatformTransactionManagerbean and in ect a DataSource
Create Spring AOP/TX definitions file classpath:/coreservletsTxContext.xml
- http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
Register advice bean
Create element
Reference the PlatformTransactionManager and DataSource beans
Define transaction ro erties
Java EE trainin : htt ://courses.coreservlets.com
Propagation (REQUIRED, REQUIRED_NEW, NESTED)
Read-only
Timeout97
7/31/2019 08 Spring Aop2
49/57
Process
Create pointcut definitions pec y program o n po n s us ng po n cu e n ons
e.g., execution(* coreservlets.CustomerBatchPersistence.*(..))
Define aspect Reference advisor and pointcut
reate e ements
Initialize the container Initialize BeanFactory using all bean definitions
classpath:/coreservletsPersistenceContext.xml
classpath:/coreservletsTxContext.xml
classpath:/coreservletsDataSourceContext.xml
Java EE trainin : htt ://courses.coreservlets.com
Access and use beans e.g., CustomerBatchPersistence dao =
(CustomerBatchPersistence) beanFactory.getBean();98
Develop Persistence Librarypublic interface CustomerBatchPersistence {
public void insert(Customer...customers);
public int getCustomerCount();
}
Java EE trainin : htt ://courses.coreservlets.com99
7/31/2019 08 Spring Aop2
50/57
Develop Persistence Library
import org.springframework.jdbc.core.simple.*;
public class SpringJdbcCustomerBatchPersistence
implements CustomerBatchPersistence {
private SimpleJdbcTemplate simpleJdbc;
public SpringJdbcCustomerBatchPersistence(DataSource dataSource) {
.}
public int getCustomerCount(){
return simpleJdbc.queryForInt("select count(*) from customer");}
Java EE trainin : htt ://courses.coreservlets.com
pu c vo nser us omer...cus omers...
}100
Develop Persistence Libraryimport org.springframework.jdbc.core.simple.*;
public class SpringJdbcCustomerBatchPersistenceimplements CustomerBatchPersistence {...public void insert(Customer...customers) {
if(customers == null){return;
for(Customer customer : customers){
simpleJdbc.update("insert into customer (id, name)"+ " values (?, ?)",
customer.getId(),customer.getName());
Java EE trainin : htt ://courses.coreservlets.com
}
}101
7/31/2019 08 Spring Aop2
51/57
7/31/2019 08 Spring Aop2
52/57
Create Spring AOP/TX
Java EE trainin : htt ://courses.coreservlets.com104
Register Transaction Manager
Java EE trainin : htt ://courses.coreservlets.com105
7/31/2019 08 Spring Aop2
53/57
Register Advice Bean
" *" " " - " "/>
Java EE trainin : htt ://courses.coreservlets.com106
Define Pointcut
...
Java EE trainin : htt ://courses.coreservlets.com107
7/31/2019 08 Spring Aop2
54/57
Define Aspect
...
Java EE trainin : htt ://courses.coreservlets.com
< aop:con g>
108
Initialize Containerimport org.springframework.context.support.*;ublic class Main
public static void main(String[]args) {BeanFactory beanFactory =new ClassPathXmlApplicationContext(new String[]{"/coreservletsPersistenceContext.xml",
"/coreservletsTxContext.xml","/coreservletsDataSourceContext.xml"});
(CustomerBatchPersistence)
beanFactory.getBean("customerBatchPersistence");...
}
Java EE trainin : htt ://courses.coreservlets.com
7/31/2019 08 Spring Aop2
55/57
Test Transaction Manager
try{
dao.insertnew Customer("dup-id","dup-name"),
new Customer("dup-id","dup-name"));throw new IllegalStateException("Failed. assertion."+ " Expected an error inserting duplicate records.");
}catch(Exception expected){
.System.out.printf("Row count changed? %s%n",rowCountModified);
if(rowCountModified){
throw new IllegalStateException("Failed. assertion."+ " Rollback failed.");
}
Java EE trainin : htt ://courses.coreservlets.com
Standard output
Row count changed? false
2008 coreservlets.com
rap-up
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
7/31/2019 08 Spring Aop2
56/57
Summary
Implementing advice AOP alliance APIs
e.g. org.aopalliance.aop.Advice As ectJ annotation su ort
@Aspect with advice type annotations; e.g. @Around
AspectJ conventions and AspectJ-typed parameters mapped byS rin AOP XML schema su ort log(joinPoint:ProceedingJoinPoint):void
throws Throwable
Spring AOP XML schema support
Java EE trainin : htt ://courses.coreservlets.com
AspectJ annotations @Aspect and @Pointcut
112
Summary Continued
Defining aspectsSpring AOP XML schema support
For referencing advice classes implementing AOP alliance APIs
For referencing advice class using AspectJ APIs
@Aspect with an advice-classifying annotation
such as @Around
equ res
Java EE trainin : htt ://courses.coreservlets.com113
7/31/2019 08 Spring Aop2
57/57
2008 coreservlets.com
ues ons
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.