Download presentation
Presentation is loading. Please wait.
1
AspectJ for Spring Developers
March 2006 AspectJ for Spring Developers Ramnivas Laddad Principal, Interface21 Author, AspectJ in Action March 2006 Copyright © Ramnivas Laddad
2
Speaker introduction Author of books and articles
AspectJ in Action: Practical Aspect-Oriented Programming Several articles on IBM developerWorks, TheServerSide, JavaWorld and other publications Consultant and trainer specializing in aspect-oriented programming and enterprise Java Speaker at many professional conferences No Fluff Just Stuff, JavaOne, JavaPolis, Software Development, EclipseCon, O’Reilly OSCON etc. Active involvement in AspectJ since its early form Over a decade of industry experience Java, J2EE, AspectJ, UML, networking, C++, and XML Copyright © Ramnivas Laddad
3
A quick introduction to AOP AspectJ AOP Spring AOP
Agenda A quick introduction to AOP AspectJ AOP Spring AOP Spring AspectJ integration Full power AspectJ Demos Q&A Copyright © Ramnivas Laddad
4
A quick intro to AOP Crosscutting concerns AOP
Functionality whose implementation spans multiple modules Many examples: Logging and tracing, Transaction management, security, caching, error handling, business rules, performance monitoring… AOP A programming methodology to help with crosscutting concerns Copyright © Ramnivas Laddad
5
Core AOP concepts Join point Pointcut Advice Introduction
An identifiable point in the execution of a program. Central, distinguishing concept in AOP Pointcut Program construct that selects join points and collects context at those points. Advice Code to be executed at a join point that has been selected by a pointcut Introduction Additional data or method to existing types, implementing new interfaces Copyright © Ramnivas Laddad
6
A Logging Aspect public aspect BankLoggingAspect {
private static Logger _logger = Logger.getLogger("banking"); public pointcut loggedOperations() : execution(* banking..*.*(..)) && !within(BankLoggingAspect); before() : loggedOperations() { Signature sig = thisJoinPointStaticPart.getSignature(); _logger.logp(Level.INFO, sig.getDeclaringType().getName(), sig.getName(), "Entering"); } Copyright © Ramnivas Laddad
7
Dynamic crosscutting: Advice
Code to be executed at a join point that has been selected by a pointcut Three kinds: Before before() : call(* ATM.*(..)) { ... } After after(Account account) returning : accountOperation(account) { Around Object around() : call(* Remote+.*(..) throws RemoteException) { try { ... proceed(); ... Retry logic } catch (...) { Copyright © Ramnivas Laddad
8
Static crosscutting Introduce new parent types Introduce new members
declare parents: banking..* implements Loggable; Introduce new members public Logger Loggable._logger; Soften exceptions declare soft: SQLException : within(banking.model..*); Compile-time errors and warning declare error : call(* Thread.*(..)) && within(javax.ejb.EnterpriseBean+) : "Use of thread disallowed from EJBs"; Copyright © Ramnivas Laddad
9
Spring AOP basics A proxy-based AOP framework
JDK proxies CGILIB proxies Targets many J2EE use cases Powerful integration with AspectJ Allowing tapping into full AOP features Copyright © Ramnivas Laddad
10
Spring AOP schematic Pointcut Advice Proxy Target Object Advisor
Copyright © Ramnivas Laddad
11
Configuring through XML: Defining advisor
<bean id="spamPreventionAdvisor" class="o.s.aop.support.DefaultPointcutAdvisor"> </bean> <property name="advice"> <bean class="example.SpamPreventionInterceptor"/> </property> <property name="pointcut"> <bean class="o.s.aop.support.JdkRegexpMethodPointcut"> <property name="pattern" value=".*send.*"/> </bean> </property> Copyright © Ramnivas Laddad
12
Configuring through XML: Creating proxy
<bean id=" erTarget" class="example. erImpl"> </bean> <bean id=" er" class="o.s.aop.framework.ProxyFactoryBean"> <property name="target" ref=" erTarget"/> <property name="interceptorNames"> <list> <value>spamPreventionAdvisor</value> </list> </property> <property name="proxyInterfaces"> <value>example. er</value> Target Advice/Advisor Proxy interface (optional) Copyright © Ramnivas Laddad
13
Bean client package example; ... public class Main {
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); er er = ( er)context.getBean(" er"); "Hi! Your paypal account..."); "Hi, I have an AspectJ question..."); } Copyright © Ramnivas Laddad
14
Advantages of proxy-based approach
Requires no special compiler Allow per-object interceptors Not per-class Less full-fledged Only method-level interception Allows easing into AOP Easy to modify applicable interceptors dynamically Copyright © Ramnivas Laddad
15
Disadvantage of proxy-based approach
Limitation of method-only interception No field-access or object creation Explicit creation of proxy required Can’t use ‘new’ to create objects Calls to ‘self’ don’t go through interceptors Low performance Typically not a huge concern, but beware Over-exposure of context Copyright © Ramnivas Laddad
16
Spring-AspectJ integration
Provides power of AspectJ in Spring Core message Spring AOP is good enough in many cases But, you often need more power Multiple level of integration Something for every one Copyright © Ramnivas Laddad
17
Spring-AspectJ: Levels of integration
No special compiler AspectJ pointcut expression With proxy mechanism Typed advice XML-based aspects definition with plain Java classes @AspectJ aspects Special compiler or weaver Full power AspectJ Copyright © Ramnivas Laddad
18
AspectJ pointcut expression
AspectJExpressionPointcut Still uses proxy-based mechanism Limitation of method-only interception <bean id="spamPreventor" class="o.s.aop.support.DefaultPointcutAdvisor"> <property name="advice"> <bean class="example.SpamPreventionInterceptor"/> </property> <property name="pointcut"> <bean class="o.s.aop.aspectj.AspectJExpressionPointcut"> <property name="expression" value="execution(* send(..))"/> </bean> Copyright © Ramnivas Laddad
19
Typed advice Problem: MethodInterceptor and its cousins take parameters of type Object. Solution: Use AspectJ style type-safe interception Copyright © Ramnivas Laddad
20
Typed advice: Defining aspect
<beans ...> <aop:config> <aop:aspect id=" LoggerBean" ref=" erLogger"> <aop:before pointcut="execution(* send(String, String)) and args(address, *)" method="log"/> </aop:aspect> </aop:config> <bean id=" erLogger" class="example. Logger"/> ... </beans> Copyright © Ramnivas Laddad
21
Plain Java aspect package example; public class EmailLogger {
public void log(JoinPoint.StaticPart tjpsp, String address) { System.err.println( "Invoking " + tjpsp.getSignature() + " for " + address); } void before(Method method, Object[] args, Object target) throws Throwable; Copyright © Ramnivas Laddad
22
Do away with XML: @AspectJ
package example; @Aspect public class Logger { @Before(execution(* send(String, String)) and args(address, *)") public void log(JoinPoint.StaticPart tjpsp, String address) { System.err.println( "Invoking " + tjpsp.getSignature() + " for " + address); } Copyright © Ramnivas Laddad
23
Using @AspectJ aspect <beans ...> <aop:autoproxy/>
<bean id=" erLogger" class="example. Logger"/> ... </beans> Copyright © Ramnivas Laddad
24
Injecting dependencies into aspects
Aspects need services, too Use Spring bean configuration to Use aspect instances as beans Inject dependencies into aspects Copyright © Ramnivas Laddad
25
Injecting dependency into aspects
<bean id="monitoringAspect" class="com.aspectivity.monitor.JDBCMonitorAspect" factory-method="aspectOf"> <property name="monitorAgent" ref="jmxMonitor"/> </bean> Automatically added methods to all aspects New in Spring 1.2 Copyright © Ramnivas Laddad
26
More power with AspectJ
When Spring’s AOP isn’t enough Weaving options Compile-time weaver Aspect and class source code class files Binary weaver (“linker”) Aspect and class source/binary files class files Load-time weaver Aspect and class binary files Weave class files when being loaded into VM Copyright © Ramnivas Laddad
27
Demos Copyright © Ramnivas Laddad
28
Injecting dependencies using Aspect
Limitations of Spring’s “traditional” DI Injection limited to beans created through configuration Not sufficient for objects created thru other mechanisms: Hibernate, JDO, fine grained objects Prevents richer domain models prescribed by domain-driven design (DDD) Solution: Use aspects to inject dependencies Copyright © Ramnivas Laddad
29
POJO with dependencies
@Configurable(" erClient") public class OrderProcessor { private er er; public void process() { ... er.send(...) } public void set er( er er) { this. er = er; Copyright © Ramnivas Laddad
30
Dependency configuration
<beans...> </beans> <aop:spring-configured/> <bean id="smtp er" .../> <bean id=" erClient"> <property name=" er" ref="smtp er"/> </bean> Copyright © Ramnivas Laddad
31
Choosing Spring vs. AspectJ AOP
Use Spring AOP when Method-only interception is sufficient Full power of AOP overwhelming Performance needs are less stringent Don’t want to use special compiler Domain object’s don’t need to be crosscutted Pre-written aspects meet your needs Use AspectJ AOP when Otherwise… Copyright © Ramnivas Laddad
32
Pragmatic usages Use Spring AOP with AspectJ Use AspectJ incrementally
Pointcut to use a more expressive selection Typed advice @AspectJ aspects Use AspectJ incrementally Development aspects Refactoring aspects Production aspects Copyright © Ramnivas Laddad
33
Summary Spring AOP is simple, yet powerful way to modularize crosscutting concerns AspectJ integration bring full power of AOP in the Spring environment Incremental path from Spring AOP to AspectJ AOP is available The fun has just began… Copyright © Ramnivas Laddad
34
Resources Spring books AspectJ books DI using aspect
Pro Spring, by Rob Harrop and Jan Machacek Professional Java Development with the Spring Framework, by Rod Johnson, Rod Johnson, Juergen Hoeller, Alef Arendsen, Thomas Risberg, Colin Sampaleanu Spring in Action, by Craig Walls AspectJ books AspectJ in Action, by Ramnivas Laddad Eclipse AspectJ, by Adrian Colyer, Andy Clement, George Harley, Matthew Webster DI using aspect Adrian Coyler, Dependency injection with AspectJ and Spring Copyright © Ramnivas Laddad
35
AOP training from the source
Core AOP: Simplifying Enterprise Applications with AOP November 7-10, Washington, DC Copyright © Ramnivas Laddad
36
World-class technical conference for the Spring community
Spring Conference: The Spring Experience 2006 December 7th – 10th, Hollywood Florida by Interface21 and NoFluffJustStuff Java Symposiums World-class technical conference for the Spring community 3 full days, 5 concurrent tracks, 60 sessions Core Spring 2.0 Core Enterprise 2.0 Core Web 2.0 Domain Driven Design Just Plain Cool Enjoy five-star beach resort and amenities Converse with core Spring team and industry experts Rod Johnson, Adrian Colyer, Ramnivas Laddad, Juergen Hoeller, etc. Registration opens in July at
37
Questions? Ramnivas Laddad Email: ramnivas.laddad@intereface21.com
Web: Blog: Training and consulting available Copyright © Ramnivas Laddad
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.