Spring AOP Spring AOP: For Live Spring & Hibernate Training, See THTT// LT
Spring AOP Spring AOP: For Live Spring & Hibernate Training, See THTT// LT
com
2008 coreservlets.com
For live Spring & Hibernate training, see courses at http://courses.coreservlets.com/. t htt // l t /
Taught by the experts that brought you this tutorial. Available at public venues, or customized versions venues can be held on-site at your organization.
C Courses d developed and t l d d taught b M t H ll ht by Marty Hall Courses developed and taught by EE Training: http://courses.coreservlets.com/ Customized Java coreservlets.com experts (edited by Marty)
Spring, Hibernate/JPA, EJB3, Ruby/Rails Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom mix of topics
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Contact [email protected] for details Developed and taught by well-known author and developer. At public venues or onsite at your location.
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.
Aspect Behavior p
Advice
Behavior to be applied to a set of program execution points In AOP terms advice encapsulates a cross-cutting terms, interest, e.g. transaction management. Advisor beans are applied to pointcuts (a set of join points)
Advice Types yp
Before
Non-critical advisor bean type Called before method execution
After returning
Non-critical advisor bean type Called after normal method execution
After throwing
Non-critical advisor bean type Called after method execution exits with an exception
Around
Critical advisor bean type yp Wraps method execution
7
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 point
Before method execution
Type
Does not i invoke method k h d Non-critical unless an error is thrown
Exception type
Checked exceptions must be coordinated with the error signature of the advised bean i t f th d i d b
Out-of-scope errors are re-thrown as java.lang.reflect.UndeclaredThrowableException RuntimeException types
precaution
10
Fulfill
before(method:Method, arguments:Object[], target:Object):void t t Obj t) id throws Throwable
13
<bean id="beforeLoggingAdvice" reference class="coreservlets.BeforeLoggingAdvice" /> <aop:config> <aop:pointcut id="customerQueryPointcut" i t t id " t Q P i t t" expression="execution(* coreservlets.CustomerQuery.*(..))" /> <aop:advisor advice-ref="beforeLoggingAdvice" pointcut ref customerQueryPointcut pointcut-ref="customerQueryPointcut" /> </aop:config> </beans>
14
Domain Beans
classpath:/coreservletsContext.xml
<beans> <bean id="customerQuery" class="coreservlets.MockCustomerQuery"> <constructor arg> <constructor-arg> <list> <bean class="coreservlets.Customer"> <property name="id" value="jjoe" /> <property name="name" value="Java Joe" /> </bean> <bean class="coreservlets.Customer"> <property name="id" value="jjohn" /> <property name="name" value="Java John" /> </bean> </list> </constructor-arg> </bean> </beans>
2008 coreservlets.com
Execution point
After normal method execution and exit
Type
Does not invoke method Non-critical unless an error is thrown
Exception type
Checked exceptions must be coordinated with the error signature of the advised bean
Out-of-scope errors are re-thrown as java.lang.reflect.UndeclaredThrowableException java lang reflect UndeclaredThrowableException RuntimeException types may be used without precaution
19
Fulfill
afterReturning(returnValue:Object, method:Method, arguments:Object[], target:Object):void throws Throwable
21
22
<bean id="afterReturningLoggingAdvice" reference class="coreservlets.AfterReturnLoggingAdvice" /> <aop:config> <aop:pointcut id="customerQueryPointcut" i t t id " t Q P i t t" expression="execution(* coreservlets.CustomerQuery.*(..))" /> <aop:advisor advice-ref="afterReturningLoggingAdvice" pointcut ref customerQueryPointcut pointcut-ref="customerQueryPointcut" /> </aop:config> </beans>
23
Domain Beans
classpath:/coreservletsContext.xml
<beans> <bean id="customerQuery" class="coreservlets.MockCustomerQuery"> <constructor arg> <constructor-arg> <list> <bean class="coreservlets.Customer"> <property name="id" value="jjoe" /> <property name="name" value="Java Joe" /> </bean> <bean class="coreservlets.Customer"> <property name="id" value="jjohn" /> <property name="name" value="Java John" /> </bean> </list> </constructor-arg> </bean> </beans>
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.
Throws Advice
Interface
org springframework aop ThrowsAdvice org.springframework.aop.ThrowsAdvice Interface is an empty marker with virtualized callbacks
Implementation
Implementations must conform to the following signature
afterThrowing(throwable:Throwable):void afterThrowing(method:Method, args:Object[], g j [], target:Object, throwable:Throwable);
Execution point p
After method exit on error Does not intercept errors originating from preceding advisors
Type
Does not invoke method Non-critical unless an error is thrown
28
Overriding
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-scope errors are re-thrown as p java.lang.reflect.UndeclaredThrowableException RuntimeException types may be used without precaution
29
Overloading by detail
A Approach i ambiguous h is bi Full method implementation is selected
30
33
Domain Beans
classpath:/coreservletsContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi http://www.w3.org/2001/XMLSchema instance xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans2.5.xsd"> <bean id="customerQuery" class="coreservlets.ErrorThrowingMockCustomerQuery"> <constructor arg <constructor-arg value="java.lang.IllegalArgumentException" /> </bean> </beans>
Java EE training: http://courses.coreservlets.com
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.
Around Advice
Interface
org.springframework.aop.MethodInterceptor
Execution point
Wraps method invocation Wraps other advisors
Excluding other Around type advisors with greater order index values Perceives return types and errors from target beans and other advisors
Type
Invokes method Critical path
40
Overriding
Exception may be overridden by re-throwing an alternate error Exceptions may also be suppressed
E Exception type ti t
Checked exceptions must be coordinated with the error signature of the advised bean g
Out-of-scope errors are re-thrown as java.lang.reflect.UndeclaredThrowableException RuntimeException types may be used without precaution
41
Fulfill
invoke(handle:MethodInvocation):Object throws Throwable
Invoke target
return handle.proceed();
44
45
46
Domain Beans
classpath:/coreservletsContext.xml
<beans> <bean id="customerQuery" class="coreservlets.MockCustomerQuery"> <constructor arg> <constructor-arg> <list> <bean class="coreservlets.Customer"> <property name="id" value="jjoe" /> <property name="name" value="Java Joe" /> </bean> <bean class="coreservlets.Customer"> <property name="id" value="jjohn" /> <property name="name" value="Java John" /> </bean> </list> </constructor-arg> </bean> </beans>
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
aop:advisor attribute order
51
52
53
before: advisor-0 before: advisor-1 after return: advisor-1 after finally: advisor-1 after return: advisor-0 after 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.
Pointcut class
Pointcut definitions are aggregated into an annotated class Classes containing pointcut elements are marked using the @Aspect annotation
56
Pointcut expression
Th pointcut definition is expressed as @Pointcut annotation The i d fi i i i d i content
57
Define pointcuts
Create a new and empty method for each pointcut
Annotate method with @Pointcut
R f Reference advice and pointcut from aspect d i d i t tf t Integrate with Spring domain beans
58
59
@Aspect
public class CoreservletsPointcuts { }
62
Define Pointcuts
import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; @Aspect public class CoreservletsPointcuts { @Pointcut("target(coreservlets.CustomerQuery)") public void queryLayer(){} @Pointcut("target(coreservlets.CustomerReport)") public void reportLayer(){} }
63
64
65
Define Aspect p
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns http://www.springframework.org/schema/beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd h // i f k / h /b / i b 2 5 d http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <bean id="loggingMethodAdvice" gg g class="coreservlets.LoggingMethodAdvice" /> <aop:config> <aop:advisor advice-ref="loggingMethodAdvice" pointcut="coreservlets.CoreservletsPointcuts.reportLayer()"/> <aop:advisor advice-ref="loggingMethodAdvice" pointcut="coreservlets.CoreservletsPointcuts.queryLayer()"/> </aop:config> /aop:co g </beans>
66
Domain Beans
classpath:/coreservletsContext.xml
<beans> b <bean id="customerReport" class="coreservlets.MockCustomerReport"> <constructor arg ref="customerQuery" <constructor-arg ref customerQuery /> </bean> <bean id="customerQuery" class="coreservlets.MockCustomerQuery"> <constructor-arg> <list> <bean class="coreservlets.Customer"> <property name= id value="jjoe" /> name="id" value= jjoe <property name="name" value="Java Joe" /> </bean> </list> </constructor-arg> </bean> </beans>
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.
Advice method
Annotated with advice classifier
@Before @AfterReturning @Aft R t i @AfterThrowing @Around Access t JoinPoint, ProceedingJoinPoint, A to JoinPoint.StaticPart See org.aspectj.lang.*
or
Configuration g
Replaces Spring AOP XML schema Annotated advisor is a Spring bean S Scanned b a b d by bean post processor
Requires element <aop:aspectj-autoproxy />
71
Define pointcuts
Create a new and empty method for each pointcut
Annotate method with @Pointcut
Bean annotations already contains advice type and pointcut reference Indirectly references aspects and pointcuts
73
74
Define Pointcuts
import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; @Aspect public class CoreservletsPointcuts { @Pointcut("target(coreservlets.CustomerQuery)") public void queryLayer(){} @Pointcut("target(coreservlets.CustomerReport)") public void reportLayer(){} }
77
78
79
80
81
Domain Beans
classpath:/coreservletsContext.xml
<beans> b <bean id="customerReport" class="coreservlets.MockCustomerReport"> <constructor arg ref="customerQuery" <constructor-arg ref customerQuery /> </bean> <bean id="customerQuery" class="coreservlets.MockCustomerQuery"> <constructor-arg> <list> <bean class="coreservlets.Customer"> <property name= id value="jjoe" /> name="id" value= jjoe <property name="name" value="Java Joe" /> </bean> </list> </constructor-arg> </bean> </beans>
coreservlets.MockCustomerReport coreservlets MockCustomerReport before coreservlets.MockCustomerReport #getReport() coreservlets.MockCustomerQuery before coreservlets.MockCustomerQuery #getCustomerByName() coreservlets.MockCustomerQuery after return coreservlets.MockCustomerReport after return
Java EE training: http://courses.coreservlets.com
2008 coreservlets.com
Advice method
Uses AspectJ API JoinPoint, ProceedingJoinPoint, or
JoinPoint.StaticPart See org aspectj lang * org.aspectj.lang.*
Pointcut
Defined by Spring AOP XML Schema
<aop:config><aop:pointcut /></aop:config>
Aspect
Defined by Spring AOP XML Schema
85
<aop:config><aop:aspect/><aop:config/>
Process
Create advice class
Optionally specify a join point parameter
Required for around advice type
D fi pointcut Define i t t
<aop:config><aop:pointcut /></aop:config>
Define aspect
<aop:config><aop:aspect/></aop:config>
88
Define Pointcut
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns http://www.springframework.org/schema/beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd h // i f k / h /b / i b 2 5 d http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <bean id="loggingAroundAdvice" gg g class="coreservlets.LoggingAroundAdvice" /> <aop:config> <aop:pointcut id="allLayers" expression="target(coreservlets.CustomerQuery) || target(coreservlets.CustomerReport)"/> </aop:config> </beans>
89
Define Pointcut
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns http://www.springframework.org/schema/beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd h // i f k / h /b / i b 2 5 d http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <bean id="loggingAroundAdvice" gg g class="coreservlets.LoggingAroundAdvice" /> <aop:config> <aop:pointcut id="allLayers" expression="target(coreservlets.CustomerQuery) i ( l ) || target(coreservlets.CustomerReport)"/> <aop:aspect ref="loggingAroundAdvice"> <aop:around pointcut ref allLayers method="log" /> pointcut-ref="allLayers" method log </aop:aspect> </aop:config> </beans> Java EE training: http://courses.coreservlets.com
90
Domain Beans
classpath:/coreservletsContext.xml
<beans> b <bean id="customerReport" class="coreservlets.MockCustomerReport"> <constructor arg ref="customerQuery" <constructor-arg ref customerQuery /> </bean> <bean id="customerQuery" class="coreservlets.MockCustomerQuery"> <constructor-arg> <list> <bean class="coreservlets.Customer"> <property name= id value="jjoe" /> name="id" value= jjoe <property name="name" value="Java Joe" /> </bean> </list> </constructor-arg> </bean> </beans>
coreservlets.MockCustomerReport coreservlets MockCustomerReport before coreservlets.MockCustomerReport #getReport() coreservlets.MockCustomerQuery before coreservlets.MockCustomerQuery #getCustomerByName() coreservlets.MockCustomerQuery after return coreservlets.MockCustomerReport after return
Java EE training: http://courses.coreservlets.com
2008 coreservlets.com
Elements
D S DataSource
Provides java.sql.Connection access/factory API g Integrates with RDBMS
DAO beans
Identifies candidate transaction boundaries
PlatformTransactionManager
Implements JDBC transaction management algorithms; e.g. JTA
94
Pointcut
Identifies persistence methods exposed by DAO beans
A Aspect t
Associates transaction management bean advisor with a pointcut
95
Process
Develop persistence library
coreservlets Customer coreservlets.Customer coreservlets.CustomerBatchPersistence coreservlets.SpringJdbcCustomerBatchPersistence
Inject dependencies
e g <bean> e.g., <constructor-arg ref="dataSource"/></bean>
Java EE training: http://courses.coreservlets.com
Process
Create advice
Re se ad ice implementation from s i Reuse advice spring-tx t
spring-tx advice delegates transaction manager algorithms to a PlatformTransactionManager service Register a PlatformTransactionManager bean and inject a DataSource g g j
97
Process
Create pointcut definitions
S if program j i points using pointcut definitions Specify join i t i i t t d fi iti e.g., execution( * coreservlets.CustomerBatchPersistence.*(..)) Create elements <aop:config><aop:pointcut/></aop:config>
Define aspect
Reference advisor and pointcut C t elements <aop:config><aop:advisor/></aop:config> Create l t fi d i / / fi
(CustomerBatchPersistence) beanFactory.getBean();
99
102
103
104
105
106
Define Pointcut
<beans> <bean id="transactionManager" id transactionManager class="org.springframework.[...].DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> ... </tx:advice> <aop:config> <aop:pointcut id="customerBatchPersistencePcd" expression="execution(* coreservlets. CustomerBatchPersistence.*(..))" /> </aop:config> </beans>
107
Define Aspect
<beans> <bean id="transactionManager" id transactionManager class="org.springframework.[...].DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> ... </tx:advice> <aop:config> <aop:pointcut id="customerBatchPersistencePcd" expression="execution(* coreservlets. CustomerBatchPersistence.*(..))" /> <aop:advisor advice-ref="transactionAdvice" pointcut-ref="customerBatchPersistencePcd" /> </aop:config> / fi </beans>
108
Initialize Container
import org.springframework.context.support.*; public class Main { public static void main(String[]args) { BeanFactory beanFactory = new ClassPathXmlApplicationContext(new String[]{ "/coreservletsPersistenceContext.xml", "/coreservletsTxContext.xml", "/coreservletsDataSourceContext.xml"}); CustomerBatchPersistence dao = (CustomerBatchPersistence) beanFactory.getBean("customerBatchPersistence"); ... }
2008 coreservlets.com
Wrap-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.
Summary y
Implementing advice
AOP alliance APIs
e.g. org.aopalliance.aop.Advice
AspectJ conventions and AspectJ-typed parameters mapped by Spring AOP XML schema support
log(joinPoint:ProceedingJoinPoint):void throws Throwable
Defining pointcuts
Spring AOP XML schema support
<aop:config><aop:pointcut/></aop:config>
AspectJ annotations
@Aspect and @Pointcut
112
Summary Continued y
Defining aspects
Spring AOP XML schema support
<aop:config><aop:advisor/></aop:config>
For referencing advice classes implementing AOP alliance APIs g p g
<aop:config><aop:aspect/></aop:config>
For referencing advice class using AspectJ APIs
AspectJ APIs
@Aspect with an advice-classifying annotation such as @Around R Requires <aop:aspectj-autoproxy/> i j /
113
2008 coreservlets.com
Questions? Q ti ?
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.