280 likes | 463 Views
Spring Proxies. Ted Young. How Were You Taught Spring?. What technologies were you introduced to first?. Why Do I Care?. Critical to implementing Spring functionality: Scoped Beans (request, session) @Transactional Support Spring Security Spring AOP Critical to the rest of the stack:
E N D
Spring Proxies Ted Young
How Were You Taught Spring? • What technologies were you introduced to first?
Why Do I Care? • Critical to implementing Spring functionality: • Scoped Beans (request, session) • @Transactional Support • Spring Security • Spring AOP • Critical to the rest of the stack: • ORMs • Unit Testing (Mocks) • Remoting • Useful elsewhere. • Using Spring without understanding proxies: • Possible, but Dangerous! • Introduce subtle problems.
Proxy Defined • General definition: • An agent authorized to act on behalf of another. • Software definition: • An object that handles one or more method calls: • Implements one or more interfaces (possibly subclasses), • All method calls routed through a single handler. • Handle method calls completely, or delegate to object(s).
Proxy Defined • Proxy Techniques: • Hand-Written • Statically Generated • Runtime Generated
Proxy Example • Consider Swing event handlers: • Log all events to a file: • ActionListener, MouseListener, ChangeListener, DocumentListener *Listener Component *Listener Component *Listener Component <<Proxy>> EventLogger File
Anatomy of a (JDK) Proxy *Listener *Listener Interfaces <<Generated>> Proxy InvocationHandler Object invoke(Object proxy, Method method, Object[] args) throws Throwable
Proxies for Testing • Unit test code that depends on external service: • Provide a proxy of the service that behaves in a controlled fashion. • Example: • Test code that interacts with credit card payment processing service. • Unit tests would: • Be slow – interacting with service over the Internet, • Be unpredictable – susceptible to unexpected network, service failures, • Be difficult – involve coordination with payment provider. • Instead, create a proxy.
EasyMock • Facilitates rapid proxying of objects for use in testing. • Four stages of operation: • Create your mock (proxy). • Record the expected behavior. • Execute your tests. • Verify actual behavior.
Footnote: Spring Mocks • Spring offers a number of mocks for common infrastructure components: • Servlet objects, • Portlet objects • JNDI. • These are not proxies. • Generally more convenient to use than EasyMock.
Proxy Delegation • Proxies often delegate to a subordinate object (target) • Often the same type(s) as the proxy. • Gives appearance that target methods are wrapped. • Advice • Veto • Manipulation • Routing
Proxy Delegation Consumer Interface <<optional>> <<Generated>> Proxy Target
Ehcache Annotations for Spring • Uses proxies to cache method calls. • Annotate a method: • Specify cache realm. • Define key, key generator. • Indicate cache eviction. • Target method will not be invoked if the results are cached. • http://code.google.com/p/ehcache-spring-annotations/
Moving Targets • During method invocation, determine which target the method is invoked on. • Pooling • Bean Scopes (request, session, thread) • Autovivification
Target Sources • Spring offers TargetSources • HotSwappableTargetSource • AbstractPoolingTargetSource (and commons-pool impl.) • PrototypeTargetSource • ThreadLocalTargetSource
Request and Session Scopes • HotSwappableTargetSource is used to implement certain bean scopes: • Request • Session
Lazy Loading in JPA, Hibernate • Defers the loading of objects, collections, LOBs until read. • Critical performance enhancement: • Queries return “references”: • Data only loaded when a property (other than the key) is read. • Facilitates batch processing. • Establish a relationship by assigning a reference instead of loading the related object. • Collections, LOBs aren’t needed “most of the time”. • Be careful in a MVC stack: • Must initialize in advance all references you intend to use in the view layer, which is often outside a transaction. • Cannot initialize reference during validation, ORM events.
Spring Transactions • Wraps a transaction around a target method: • Handles various rollback situations. • Takes care of all clean up. • Removes lots of boilerplate code. • Eliminates lower level dependencies. • Offers numerous configuration options. • Can target methods with XML or annotations.
Spring Security • Determine if the principle can invoke the target method: • Privileges, • ACLs of parameters and return value. • Filter the parameters, return value based on principle. • Uses Annotation and SpEL.
Reusable Proxies • What we need: • The proxy implementation (class), • A method to instantiate the proxy (factory), • Optionally, a mechanism to execute the proxy automatically during the execution of the program: • A way to specify which targets + methods should be handled by the proxy.
Spring AOP • AOP is way to abstract cross-cutting concerns. • Spring’s AOP implementation uses proxies. • Often the most convenient way to create proxies: • Does not depend on a specific proxy technology. • Eliminates low-level concerns. • Proxies are Spring-managed. • Targets can be specified declaratively.
AOP Core Concepts • Aspect: a modularization of a concern (i.e. a class). • Join Point: a point during the execution of a program (i.e. method). • Pointcut: an expression that selects (matches) one or more join points. • Advice: applies functionality of an aspect to the join points selected by a pointcut.
The Obligatory Example • A tracing aspect: • Logs the execution of all public methods.
Spring AOP Limitations • Uses Proxies: • Can only advise managed beans: • Can’t advise ORM managed entities, JSP tag libraries, etc. • Spring suppoprts advising FreeMarker and Velocity macros, JSR303 validators. • Can’t advise advice. • However, advice can be configured. • Can only advice public methods. • Watch out for self-invocation! • Internal calls, calls to super-classes, calls to abstract methods.
Self-Invocation • @Trace("This gets traced.") • publicvoidcalledFromExternalObject() { • calledInternally(); • } • @Trace("This DOES NOT get traced.") • publicvoidcalledInternally() { • }
Proxy Technologies • JDK Proxies: • Native to JDK since 1.3 • Proxy only interfaces. • The default method used by Spring. • CGLIB: • Requires CGLIB binaries. • Proxies interfaces and classes (by generating subclasses). • Calls constructor twice. • Used by Spring when target does not implement interfaces. • Spring • Provides technology independent abstraction over implementation.