1 AspectJ for Spring DevelopersMarch 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 articlesAspectJ 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 AOPFunctionality 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 IntroductionAn 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: AdviceCode 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 membersdeclare 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 frameworkJDK 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 AdvisorCopyright © Ramnivas Laddad
11 Configuring through XML: Defining advisor
12 Configuring through XML: Creating proxy
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 approachRequires 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 approachLimitation 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 integrationProvides 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 integrationNo 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 expressionAspectJExpressionPointcut Still uses proxy-based mechanism Limitation of method-only interception
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
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: @AspectJpackage 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
24 Injecting dependencies into aspectsAspects 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
26 More power with AspectJWhen 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 AspectLimitations 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
31 Choosing Spring vs. AspectJ AOPUse 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 incrementallyPointcut 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 aspectPro 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 sourceCore 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: [email protected]Web: Blog: Training and consulting available Copyright © Ramnivas Laddad