Spring Proxies Ted Young How Were You Taught

  • Slides: 28
Download presentation
Spring Proxies Ted Young

Spring Proxies Ted Young

How Were You Taught Spring? • What technologies were you introduced to first?

How Were You Taught Spring? • What technologies were you introduced to first?

Why Do I Care? • Critical to implementing Spring functionality: • • Scoped Beans

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.

What Is a Proxy?

What Is a Proxy?

Proxy Defined • General definition: • An agent authorized to act on behalf of

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 Defined • Proxy Techniques: • Hand-Written • Statically Generated • Runtime Generated

Proxy Example • Consider Swing event handlers: • Log all events to a file:

Proxy Example • Consider Swing event handlers: • Log all events to a file: • Action. Listener, Mouse. Listener, Change. Listener, Document. Listener Component *Listener <<Proxy>> Event. Logger File

Anatomy of a (JDK) Proxy *Listener Interfaces <<Generated>> Proxy Invocation. Handler Object invoke(Object proxy,

Anatomy of a (JDK) Proxy *Listener Interfaces <<Generated>> Proxy Invocation. Handler Object invoke(Object proxy, Method method, Object[] args) throws Throwable

Proxies for Testing • Unit test code that depends on external service: • Provide

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.

Easy. Mock • Facilitates rapid proxying of objects for use in testing. • Four

Easy. Mock • 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:

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 Easy. Mock.

Proxy Delegation • Proxies often delegate to a subordinate object (target) • Often the

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

Proxy Delegation Consumer Interface <<optional>> <<Generated>> Proxy Target

Ehcache Annotations for Spring • Uses proxies to cache method calls. • Annotate a

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.

Moving Targets • During method invocation, determine which target the method is invoked on. • Pooling • Bean Scopes (request, session, thread) • Autovivification

Target Sources • Spring offers Target. Sources • • Hot. Swappable. Target. Source Abstract.

Target Sources • Spring offers Target. Sources • • Hot. Swappable. Target. Source Abstract. Pooling. Target. Source (and commons-pool impl. ) Prototype. Target. Source Thread. Local. Target. Source

Request and Session Scopes • Hot. Swappable. Target. Source is used to implement certain

Request and Session Scopes • Hot. Swappable. Target. Source is used to implement certain bean scopes: • Request • Session

Lazy Loading in JPA, Hibernate • Defers the loading of objects, collections, LOBs until

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

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,

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 Sp. EL.

Reusable Proxies • What we need: • The proxy implementation (class), • A method

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

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).

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

The Obligatory Example • A tracing aspect: • Logs the execution of all public methods.

Proxies versus Aspects Concept Proxy Aspect Proxy Class Auto-Generated Proxy Instance Proxy. new. Proxy.

Proxies versus Aspects Concept Proxy Aspect Proxy Class Auto-Generated Proxy Instance Proxy. new. Proxy. Instance Spring Managed Proxy Logic Invocation. Handler Aspects Target(s) Manually Established Configuration (Pointcuts) Injection None Spring Managed

Spring AOP Limitations • Uses Proxies: • Can only advise managed beans: • Can’t

Spring AOP Limitations • Uses Proxies: • Can only advise managed beans: • Can’t advise ORM managed entities, JSP tag libraries, etc. • Spring suppoprts advising Free. Marker and Velocity macros, JSR 303 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. ") public void called. From. External. Object() { called. Internally();

Self-Invocation @Trace("This gets traced. ") public void called. From. External. Object() { called. Internally(); } @Trace("This DOES NOT get traced. ") public void called. Internally() { }

Proxy Technologies • JDK Proxies: • Native to JDK since 1. 3 • Proxy

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.