Spring Proxies

28
Spring Proxies Ted Young

description

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: - PowerPoint PPT Presentation

Transcript of Spring Proxies

Page 1: Spring Proxies

Spring ProxiesTed Young

Page 2: Spring Proxies

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

Page 3: Spring Proxies

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.

Page 4: Spring Proxies

What Is a Proxy?

Page 5: Spring Proxies

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

Page 6: Spring Proxies

Proxy Defined• Proxy Techniques:• Hand-Written• Statically Generated• Runtime Generated

Page 7: Spring Proxies

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

• ActionListener, MouseListener, ChangeListener, DocumentListener

<<Proxy>>

EventLogger

*Listener*Listener

*ListenerComponent

ComponentComponent

File

Page 8: Spring Proxies

Anatomy of a (JDK) Proxy

<<Generated>>

Proxy

*Listener*Listener

Interfaces

InvocationHandlerObject invoke(Object proxy, Method method, Object[] args) throws Throwable

Page 9: Spring Proxies

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.

Page 10: Spring Proxies

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.

Page 11: Spring Proxies

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.

Page 12: Spring Proxies

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

Page 13: Spring Proxies

Proxy Delegation

<<Generated>>

Proxy

InterfaceConsumer

Target

<<optional>>

Page 14: Spring Proxies

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/

Page 15: Spring Proxies

Moving Targets• During method invocation, determine which target the

method is invoked on.• Pooling• Bean Scopes (request, session, thread)• Autovivification

Page 16: Spring Proxies

Target Sources• Spring offers TargetSources• HotSwappableTargetSource • AbstractPoolingTargetSource (and commons-pool impl.) • PrototypeTargetSource• ThreadLocalTargetSource

Page 17: Spring Proxies

Request and Session Scopes• HotSwappableTargetSource is used to implement certain bean

scopes:• Request• Session

Page 18: Spring Proxies

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.

Page 19: Spring Proxies

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.

Page 20: Spring Proxies

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.

Page 21: Spring Proxies

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.

Page 22: Spring Proxies

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.

Page 23: Spring Proxies

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.

Page 24: Spring Proxies

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

Page 25: Spring Proxies

Proxies versus AspectsConcept Proxy Aspect

Proxy Class Auto-Generated Auto-Generated

Proxy Instance Proxy.newProxyInstance Spring Managed

Proxy Logic InvocationHandler Aspects

Target(s) Manually Established Configuration (Pointcuts)

Injection None Spring Managed

Page 26: Spring Proxies

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.

Page 27: Spring Proxies

Self-Invocation

@Trace("This gets traced.")public void calledFromExternalObject() {

calledInternally();}

@Trace("This DOES NOT get traced.")public void calledInternally() {}

Page 28: Spring Proxies

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.