0% found this document useful (0 votes)
71 views57 pages

Spring AOP Spring AOP: For Live Spring & Hibernate Training, See THTT// LT

Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views57 pages

Spring AOP Spring AOP: For Live Spring & Hibernate Training, See THTT// LT

Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

2008 coreservlets.

com

Spring AOP 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, 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.

Topics in This Section p


Implementing aspect behavior AspectJ APIs and annotations Spring AOP application

Java EE training: http://courses.coreservlets.com

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)

Spring advisor bean


Implementation
POJOs encoding advice

Integration (one of the following)


Special interfaces org.aopalliance.aop.Advice Methods annotated with AspectJ annotations and defined with AspectJ parameters types
6

Java EE training: http://courses.coreservlets.com

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

Java EE training: http://courses.coreservlets.com

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

Java EE training: http://courses.coreservlets.com

Before Advice Guidelines


Uses
Input validation Auditing/logging

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

may be used without

10

Java EE training: http://courses.coreservlets.com

Before Advice Process


Create new advice class
Implement
org.springframework.aop.MethodBeforeAdvice

Fulfill
before(method:Method, arguments:Object[], target:Object):void t t Obj t) id throws Throwable

Register advice as a Spring bean g p g


<bean/>

Reference from aspect


Associate with a pointcut
11

Integrate with Spring domain beans

Java EE training: http://courses.coreservlets.com

Create Before Advice Class


import java.lang.reflect.Method; import org.springframework.aop.MethodBeforeAdvice; public class BeforeLoggingAdvice implements MethodBeforeAdvice { public void before(Method method, Object[] args, Object target) throws Throwable { Logger.getLogger(target.getClass()).debug( target.getClass().getSimpleName() + "#" + method.toGenericString() + ". args=" + Arrays.toString(args)); } }
12

Java EE training: http://courses.coreservlets.com

Register Before Advice Bean g


<?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="beforeLoggingAdvice" class="coreservlets.BeforeLoggingAdvice" /> </beans>

13

Java EE training: http://courses.coreservlets.com

Reference From 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">
Advisor

<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

Java EE training: http://courses.coreservlets.com

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>

Java EE training: http://courses.coreservlets.com

Integrate Advice with Domain Beans


import org.springframework.context.support.*; public class Main { public static void main(String[]args) { BeanFactory beanFactory = new ClassPathXmlApplicationContext( "/coreservletsContext.xml", "/coreservletsAopContext xml"); /coreservletsAopContext.xml ); ... } }

Java EE training: http://courses.coreservlets.com

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", "/coreservletsAopContext xml"}); /coreservletsAopContext.xml }); CustomerQuery query = (CustomerQuery) beanFactory.getBean("customerQuery"); Customer customer = query.getCustomerByName("Java Joe"); } }
Standard output

MockCustomerQuery#public abstract coreservlets.Customer coreservlets.CustomerQuery.getCustomerByName(java.lang.S tring). args=[Java Joe]


Java EE training: http://courses.coreservlets.com

2008 coreservlets.com

After Returning Aft R t i 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.

After Returning Advice g


Interface
org.springframework.aop.AfterReturningAdvice i i i

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

Java EE training: http://courses.coreservlets.com

After Returning Advice g


Create new advice class
Implement
org.springframework.aop.AfterReturningAdvice

Fulfill
afterReturning(returnValue:Object, method:Method, arguments:Object[], target:Object):void throws Throwable

Register advice as a Spring bean


<bean/>

Reference from aspect


Associate with a pointcut

Integrate with Spring domain beans


20

Java EE training: http://courses.coreservlets.com

After Returning Advice Class g


import java.lang.reflect.Method; import org.springframework.aop. AfterReturningAdvice; public class BeforeLoggingAdvice implements AfterReturningAdvice { public void afterReturning(Object returnValue, Method method, Object[] args, args Object target) throws Throwable { Logger.getLogger(target.getClass()).debug( "exit=return[" + returnValue + "]"); } }

21

Java EE training: http://courses.coreservlets.com

Register After Returning Advice Bean


<?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="afterReturningLoggingAdvice" class="coreservlets.AfterReturnLoggingAdvice" /> </beans>

22

Java EE training: http://courses.coreservlets.com

Reference From 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">
Advisor

<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

Java EE training: http://courses.coreservlets.com

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>

Java EE training: http://courses.coreservlets.com

Integrate Advice with Domain Beans


import org.springframework.context.support.*; public class Main { public static void main(String[]args) { BeanFactory beanFactory = new ClassPathXmlApplicationContext( "/coreservletsContext.xml", "/coreservletsAopContext xml"); /coreservletsAopContext.xml ); ... } }

Java EE training: http://courses.coreservlets.com

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", "/coreservletsAopContext xml"}); /coreservletsAopContext.xml }); CustomerQuery query = (CustomerQuery) beanFactory.getBean("customerQuery"); Customer customer = query.getCustomerByName("Java Joe"); } }
Standard output

exit=return[Customer id=jjoe, name=Java Joe]


Java EE training: http://courses.coreservlets.com

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

Java EE training: http://courses.coreservlets.com

Throws Advice Guidelines


Uses
Adapting API error behavior Error conformance to a domain type

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

Java EE training: http://courses.coreservlets.com

Throws Advice Guidelines


Overloading by type
Advice bean may overload methods to support varying error types The most precise advising method is selected p the p g per Throwable type

Overloading by detail
A Approach i ambiguous h is bi Full method implementation is selected

30

Java EE training: http://courses.coreservlets.com

Throws Advice Process


Create new advice class
Implement
org.springframework.aop.ThrowsAdvice

Define one or more interceptor methods p


afterThrowing(throwable:Throwable):void afterThrowing(method:Method, args:Object[], target:Object, throwable:Throwable);

Register advice as a Spring bean


<bean/>

Reference from aspect


Associate with a pointcut

Integrate with Spring domain beans


31

Java EE training: http://courses.coreservlets.com

Throws Advice Class


import java.lang.reflect.Method; import org.springframework.aop.ThrowsAdvice; public class ThrowsLoggingAdvice implements ThrowsAdvice { public void afterThrowing(Method method , Object[] arguments , Object target , IllegalArgumentException ex) throws Throwable { Logger.getLogger(target.getClass()).debug( "afterThrowing: IllegalArgumentException ); afterThrowing: IllegalArgumentException"); } public void afterThrowing(Method method , Object[] arguments , Object target , IllegalStateException ex) throws Throwable { Logger.getLogger(target.getClass()).debug( "afterThrowing: Ill " ft Th i IllegalStateException"); lSt t E ti ") } }
32

Java EE training: http://courses.coreservlets.com

Register Throws Advice Bean g


<?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="throwsLoggingAdvice" class="coreservlets.ThrowsLoggingAdvice" /> </beans>

33

Java EE training: http://courses.coreservlets.com

Reference From 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="throwsLoggingAdvice" Advisor reference class="coreservlets.ThrowsLoggingAdvice" /> <aop:config> <aop:pointcut id="customerQueryPointcut" i t t id " t Q P i t t" expression="execution(* coreservlets.CustomerQuery.*(..))" /> <aop:advisor advice-ref="throwsLoggingAdvice" pointcut ref customerQueryPointcut pointcut-ref="customerQueryPointcut" /> </aop:config> </beans>
34

Java EE training: http://courses.coreservlets.com

Mock Domain Class


public class ErrorThrowingMockCustomerQuery implements CustomerQuery { private Class<? extends RuntimeException>throwableType; public ErrorThrowingMockCustomerQuery ( Class<? extends RuntimeException>throwableType){ this.throwableType = throwableType; } public Customer getCustomerByName(String name) { try{ throw throwableType.newInstance(); } catch(InstantiationException e){ ... } }
35

Java EE training: http://courses.coreservlets.com

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

Integrate Advice with Domain Beans


import org.springframework.context.support.*; public class Main { public static void main(String[]args) { BeanFactory beanFactory = new ClassPathXmlApplicationContext( "/coreservletsContext.xml", "/coreservletsAopContext xml"); /coreservletsAopContext.xml ); ... } }

Java EE training: http://courses.coreservlets.com

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", "/coreservletsAopContext.xml"}); CustomerQuery query = (CustomerQuery) beanFactory getBean("customerQuery"); beanFactory.getBean( customerQuery ); Customer customer = query.getCustomerByName("Java Joe"); } }
Standard output

afterThrowing: IllegalArgumentException Exception in thread "main" i i h d i java.lang.IllegalArgumentException


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

Java EE training: http://courses.coreservlets.com

Around Advice Guidelines


Uses
Transaction management Full templating cases

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

Java EE training: http://courses.coreservlets.com

Around Advice Process


Create new advice class
Implement
org.springframework.aop.MethodInterceptor

Fulfill
invoke(handle:MethodInvocation):Object throws Throwable

Invoke target
return handle.proceed();

Register advice as a Spring bean


<bean/>

Reference from aspect


Associate with a pointcut p

Integrate with Spring domain beans


42

Java EE training: http://courses.coreservlets.com

Around Advice Class


import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; public class NamedAroundAdvice implements MethodInterceptor { private String name; public NamedAroundAdvice(String name){ this.name = name; } public Object invoke(MethodInvocation invocation) throws Throwable { ... } }
43

Java EE training: http://courses.coreservlets.com

Around Advice Class Continued


... public Object invoke(MethodInvocation invocation) 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); throw t; th t } finally{ log.debug( after log debug("after finally: " + this.name); this name); } } Java EE training: http://courses.coreservlets.com ...

44

Register Around Advice Bean g


<?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="namedAroundAdvice" class="coreservlets.NamedAroundAdvice"> <property name="name" value="namedAroundAdvice" /> </bean> /b </beans>

45

Java EE training: http://courses.coreservlets.com

Reference From 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="namedAroundAdvice" Advisor Ad i class="coreservlets.NamedAroundAdvice"> reference <property name="name" value="namedAroundAdvice" /> </bean> <aop:config> <aop:pointcut id="customerQueryPointcut" expression="execution(* coreservlets.CustomerQuery.*(..))" /> <aop:advisor advice ref= namedAroundAdvice advice-ref="namedAroundAdvice" pointcut-ref="customerQueryPointcut" /> </aop:config> </beans> Java EE training: http://courses.coreservlets.com

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>

Java EE training: http://courses.coreservlets.com

Integrate Advice with Domain Beans


import org.springframework.context.support.*; public class Main { public static void main(String[]args) { BeanFactory beanFactory = new ClassPathXmlApplicationContext( "/coreservletsContext.xml", "/coreservletsAopContext xml"); /coreservletsAopContext.xml ); ... } }

Java EE training: http://courses.coreservlets.com

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", "/coreservletsAopContext.xml"}); CustomerQuery query = (CustomerQuery) beanFactory getBean("customerQuery"); beanFactory.getBean( customerQuery ); Customer customer = query.getCustomerByName("Java Joe"); } }
Standard output

before: namedAroundAdvice after return: namedAroundAdvice after finally: namedAroundAdvice


Java EE training: http://courses.coreservlets.com

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

Java EE training: http://courses.coreservlets.com

Around Advice Class


public class NamedAroundAdvice implements MethodInterceptor { ... public Object invoke(MethodInvocation inv) throws Throwable { try{ log.debug("before: " + this.name); l d b ( b f hi ) Object returnValue = inv.proceed(); log.debug("after return: " + this.name); return returnValue; } catch(Throwable t){ log.debug("after throws: " + this.name); throw t; } finally{ log.debug("after log debug("after finally: " + this.name); this name); } } } Java EE training: http://courses.coreservlets.com

52

Configure Aspect Order g p


<?xml version="1.0" encoding="UTF-8"?> <beans> <bean id="advisor-0" class="coreservlets.NamedAroundAdvice"> <property name="name" value="advisor-0" /> </bean> <bean id="advisor-1" class="coreservlets.NamedAroundAdvice"> <property name="name" value="advisor-1" /> </bean> <aop:config> <aop:pointcut id="customerQueryPointcut" expression="execution(* coreservlets.CustomerQuery.*(..))" /> <aop:advisor advice-ref="advisor-0" order="0" pointcut-ref="customerQueryPointcut" /> <aop:advisor advice-ref="advisor-1" order="1" pointcut-ref="customerQueryPointcut" /> </aop:config> Java EE training: http://courses.coreservlets.com </beans>

53

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", "/coreservletsAopContext.xml"}); CustomerQuery query = (CustomerQuery) beanFactory getBean("customerQuery"); beanFactory.getBean( customerQuery ); Customer customer = query.getCustomerByName("Java Joe"); } } Standard output p

before: advisor-0 before: advisor-1 after return: advisor-1 after finally: advisor-1 after return: advisor-0 after finally: advisor-0

Java EE training: http://courses.coreservlets.com

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.

AspectJ Pointcuts Introduction p


Design
Reuses class and method namespace for enumerating pointcut definitions S b tit t f S i AOP XML schema support Substitute for Spring h t
<aop:config><aop:pointcut/></aop:config>

Pointcut class
Pointcut definitions are aggregated into an annotated class Classes containing pointcut elements are marked using the @Aspect annotation

56

Java EE training: http://courses.coreservlets.com

AspectJ Pointcuts Introduction Continued


Pointcut element
An annotated method, @Pointcut, represents a single pointcut definition The class and method combination is the unique pointcut q p identifier
<full classname>.<method name>() Pointcut methods are public instance methods, accept no arguments, and specify a void return type

Pointcut expression
Th pointcut definition is expressed as @Pointcut annotation The i d fi i i i d i content

57

Java EE training: http://courses.coreservlets.com

AspectJ Pointcuts Process p


Create new pointcut definitions class
Annotate class with @Aspect

Define pointcuts
Create a new and empty method for each pointcut
Annotate method with @Pointcut

Specify pointcut definition as @Pointcut annotation content

C Create advice class t d i l


Implement an AOP Alliance interface
org.aopalliance.aop.Advice g p p

Register advice as a Spring bean


<bean/>

R f Reference advice and pointcut from aspect d i d i t tf t Integrate with Spring domain beans
58

Java EE training: http://courses.coreservlets.com

Select Join Points


public interface CustomerQuery { public Customer getCustomerByName(String name); } public interface CustomerReport { public String getReport(String customerName); }

59

Java EE training: http://courses.coreservlets.com

Select Join Points Continued


public class MockCustomerQuery implements CustomerQuery { private List<Customer> customers; public MockCustomerQuery(List<Customer> customers) { this.customers = customers != null ? customers : new ArrayList<Customer>(); }

public Customer getCustomerByName(String name) {


for(Customer c : customers){ if(c.getName().equals(name)){ return c; } } return null; ll } }
60

Java EE training: http://courses.coreservlets.com

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 ? customer.toString() : null; }
61

Java EE training: http://courses.coreservlets.com

Create Pointcut Definitions Class


import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class CoreservletsPointcuts { }

62

Java EE training: http://courses.coreservlets.com

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

Java EE training: http://courses.coreservlets.com

Create Advice Class


public class LoggingMethodAdvice implements MethodInterceptor { public 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{ Logger.getLogger(i.getThis().getClass()).debug(buf); L tL (i tThi () tCl ()) d b (b f) } } Java EE training: http://courses.coreservlets.com }

64

Register Advice Bean g


<?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" class="coreservlets.LoggingMethodAdvice" /> </beans> /b

65

Java EE training: http://courses.coreservlets.com

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

Java EE training: http://courses.coreservlets.com

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>

Java EE training: http://courses.coreservlets.com

Access and Use Beans


import org.springframework.context.support.*; public class Main { public 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] - arg values: Java Joe - ex return : Customer id=jjoe, name=Java Joe LoggingMethodAdvice - target : coreservlets.MockCustomerReport - method : getReport[class java.lang.String] - arg values: Java Joe - ex return : Customer id=jjoe, name=Java Joe
Java EE training: http://courses.coreservlets.com

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.

AspectJ Advice Introduction p


Advice class
No special interfaces Annotated with @Aspect

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

O l around advice is critical to target execution Only d d i i iti l t t t ti


70

Java EE training: http://courses.coreservlets.com

AspectJ Advice Introduction Continued


Annotation content
Specifies pointcut definition as a pointcut expression e.g., @Around("Pointcuts.layer()") e g @Around(value "Pointcuts layer()" e.g., @Around(value="Pointcuts.layer()",
argNames="")

Annotation p ope ty argNames otat o property a gNa es


Supplies advice method parameter names to pointcut

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

Java EE training: http://courses.coreservlets.com

AspectJ Pointcuts Process p


Create new pointcut definitions class
Annotate class with @Aspect

Define pointcuts
Create a new and empty method for each pointcut
Annotate method with @Pointcut

Specify pointcut definition as @Pointcut annotation content

Create advice class


Annotate class with @Aspect Annotate advice method with advice type classifying annotation
e.g. @Around

S if pointcut reference as advice type annotation content Specify i t t f d i t t ti t t


e.g. @Around("Pointcuts.layer()")
72

Java EE training: http://courses.coreservlets.com

AspectJ Pointcuts Process Continued


Skip <aop:config/> Register advice as a Spring bean
<bean/>

Bean annotations already contains advice type and pointcut reference Indirectly references aspects and pointcuts

S Scan A AspectJ annotations tJ t ti


Add post processor instruction to bean definitions <aop:aspectj-autoproxy /> p p j p y /

Integrate with Spring domain beans

73

Java EE training: http://courses.coreservlets.com

Select Join Points


public interface CustomerQuery { public Customer getCustomerByName(String name); } public interface CustomerReport { public String getReport(String customerName); }

74

Java EE training: http://courses.coreservlets.com

Select Join Points Continued


public class MockCustomerQuery implements CustomerQuery { private List<Customer> customers; public MockCustomerQuery(List<Customer> customers) { this.customers = customers != null ? customers : new ArrayList<Customer>(); }

public Customer getCustomerByName(String name) {


for(Customer c : customers){ if(c.getName().equals(name)){ return c; } } return null; ll } }
75

Java EE training: http://courses.coreservlets.com

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 ? customer.toString() : null; }
76

Java EE training: http://courses.coreservlets.com

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

Java EE training: http://courses.coreservlets.com

Create Advice Class


import import import import org.apache.log4j.Logger; org.aspectj.lang.ProceedingJoinPoint; org.aspectj.lang.annotation.Around; org.aspectj.lang.annotation.Aspect;

@Aspect public class LoggingAroundAdvice { }

78

Java EE training: http://courses.coreservlets.com

Create Advice Class


@Aspect public class LoggingAroundAdvice { @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"); log.debug( # log debug("#" + jp.getSignature().getName() + "()"); jp getSignature() getName() () ); Object returnValue = jp.proceed(); log.debug("after return"); return returnValue; } catch(Throwable t){ log.debug("after throws"); throw t; th t } } Java EE training: http://courses.coreservlets.com }

79

Register Advice Bean g


<?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" class="coreservlets.LoggingAroundAdvice" /> </beans> /b

80

Java EE training: http://courses.coreservlets.com

Register Bean Postprocessor g 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="loggingAroundAdvice" class="coreservlets.LoggingAroundAdvice" /> <aop:aspectj-autoproxy/> j / </beans>

81

Java EE training: http://courses.coreservlets.com

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>

Java EE training: http://courses.coreservlets.com

Access and Use Beans


import org.springframework.context.support.*; public class Main { public static void main(String[]args) { BeanFactory beanFactory = ...; CustomerReport reportService = (CustomerReport) beanFactory.getBean("customerReport"); reportService.getReport("Java Joe"); } }
Standard output

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

AspectJ Advice with Spring AOP p g XML Schema


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.

AspectJ Advice with Spring AOP XML Schema


Advice class
No special interfaces No annotations

Advice method
Uses AspectJ API JoinPoint, ProceedingJoinPoint, or
JoinPoint.StaticPart See org aspectj lang * org.aspectj.lang.*

Only around advice is critical to target execution

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/>

Java EE training: http://courses.coreservlets.com

Process
Create advice class
Optionally specify a join point parameter
Required for around advice type

Specify return type for around advice type

Register advice bean


<bean/>

D fi pointcut Define i t t
<aop:config><aop:pointcut /></aop:config>

Declare pointcut ID and expression p p

Define aspect
<aop:config><aop:aspect/></aop:config>

Reference pointcut definition Reference advisor bean


86

Java EE training: http://courses.coreservlets.com

Create Advice Class


import org.apache.log4j.Logger; import org.aspectj.lang.ProceedingJoinPoint; 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() + "()"); Object returnValue = joinPoint proceed(); joinPoint.proceed(); log.debug("after return"); return returnValue; } catch(Throwable t){ log.debug("after throws"); throw t; } } }
87

Java EE training: http://courses.coreservlets.com

Register Advice Bean g


<?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" class="coreservlets.LoggingAroundAdvice" /> </beans> /b

88

Java EE training: http://courses.coreservlets.com

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

Java EE training: http://courses.coreservlets.com

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>

Java EE training: http://courses.coreservlets.com

Access and Use Beans


import org.springframework.context.support.*; public class Main { public static void main(String[]args) { BeanFactory beanFactory = ...; CustomerReport reportService = (CustomerReport) beanFactory.getBean("customerReport"); reportService.getReport("Java Joe"); } }
Standard output

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

Spring S i AOP Application


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.

JDBC Transaction Management using AOP


Application
Transaction management over DAO persistence methods

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

Java EE training: http://courses.coreservlets.com

JDBC Transaction Management using AOP


Spring AOP
Advice
Abstracts transaction management services as a Spring AOP bean advisor

Pointcut
Identifies persistence methods exposed by DAO beans

A Aspect t
Associates transaction management bean advisor with a pointcut

95

Java EE training: http://courses.coreservlets.com

Process
Develop persistence library
coreservlets Customer coreservlets.Customer coreservlets.CustomerBatchPersistence coreservlets.SpringJdbcCustomerBatchPersistence

Register Spring IoC and AOP JARs


spring-core.jar, spring-context.jar, spring-beans.jar, spring-aop.jar, aopalliance.jar, aspectjweaver.jar, cglib.jar, commons-logging.jar

Create the bean definitions file


e.g., classpath:/coreservletsPersistenceContext.xml

Register persistence beans


e g <bean id="customerBatchPersistence" e.g., id= customerBatchPersistence class="coreservlets.CustomerBatchPersistence"/>

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

Create Spring AOP/TX definitions file


classpath:/coreservletsTxContext.xml Register spring tx NS spring-tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd

Register advice bean


Create advisor bean declaration Create <tx:advice/> element
Reference the PlatformTransactionManager and DataSource beans Define transaction properties p p Propagation (REQUIRED, REQUIRED_NEW, NESTED) Read-only Timeout Java EE training: http://courses.coreservlets.com

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

Initialize the container


Initialize BeanFactory using all bean definitions classpath:/coreservletsPersistenceContext.xml classpath:/coreservletsTxContext.xml classpath:/coreservletsDataSourceContext.xml

Access and use beans


e.g., CustomerBatchPersistence dao =
98

(CustomerBatchPersistence) beanFactory.getBean();

Java EE training: http://courses.coreservlets.com

Develop Persistence Library p y


public interface CustomerBatchPersistence { public void insert(Customer...customers); public int getCustomerCount(); }

99

Java EE training: http://courses.coreservlets.com

Develop Persistence Library p y


import org.springframework.jdbc.core.simple.*; public class SpringJdbcCustomerBatchPersistence implements CustomerBatchPersistence { private SimpleJdbcTemplate simpleJdbc; public SpringJdbcCustomerBatchPersistence(DataSource dataSource) { this.simpleJdbc this simpleJdbc = new SimpleJdbcTemplate(dataSource); } public int getCustomerCount(){ return simpleJdbc.queryForInt("select count(*) from customer"); } public void i bli id insert(Customer...customers) { t(C t t ) ... }
100

Java EE training: http://courses.coreservlets.com

Develop Persistence Library p y


import org.springframework.jdbc.core.simple.*; public class SpringJdbcCustomerBatchPersistence implements 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()); } } }
101

Java EE training: http://courses.coreservlets.com

Select Join Points


public interface CustomerBatchPersistence { public void insert(Customer...customers); public int getCustomerCount(); }

102

Java EE training: http://courses.coreservlets.com

Create Bean Definitions


classpath:/coreservletsPersistenceContext.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" p g xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans2.5.xsd"> <bean id="customerBatchPersistence" class="coreservlets.SpringCustomerBatchPersistence"> <constructor-arg ref="dataSource" / g /> </bean> </beans>

103

Java EE training: http://courses.coreservlets.com

Create Spring AOP/TX Definitions File


<?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" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www springframework org/schema/aop/spring-aop-2 5 xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> </beans>

104

Java EE training: http://courses.coreservlets.com

Register Transaction Manager g g


<?xml version="1.0" encoding="UTF-8"?> <beans> <bean id="transactionManager" class="org.springframework....DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>

105

Java EE training: http://courses.coreservlets.com

Register Advice Bean tx:advice


<beans> <bean id="transactionManager" id transactionManager class="org.springframework.[...].DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name= get* propagation="REQUIRED" read-only="true" name="get*" propagation= REQUIRED read-only= true /> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> </beans>

106

Java EE training: http://courses.coreservlets.com

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

Java EE training: http://courses.coreservlets.com

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

Java EE training: http://courses.coreservlets.com

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"); ... }

Java EE training: http://courses.coreservlets.com

Test Transaction Manager g


try{ dao.insert( new 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){ boolean rowCountModified = count != dao getCustomerCount(); dao.getCustomerCount(); System.out.printf("Row count changed? %s%n", rowCountModified); if(rowCountModified){ throw new IllegalStateException("Failed. assertion." + " Rollback failed."); } } Standard output

Row count changed? false


Java EE training: http://courses.coreservlets.com

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 annotation support p pp


@Aspect with advice type annotations; e.g. @Around

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

Java EE training: http://courses.coreservlets.com

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

Java EE training: http://courses.coreservlets.com

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.

You might also like