Runtime Proxies
Wrap an interface implementation at runtime through a builder API. JDK dynamic proxies, no AOP framework.
The runtime side of ProxyBuilder is one class: DynamicProxyBuilder. You give
it an interface and an instance; you chain on the behaviour you want; you call
.build() and receive a proxy that you can hand to any consumer of the
interface.
What you can add to a runtime proxy
- Pre-actions — run before every method invocation.
- Post-actions — run after every method invocation.
- Security rules — return
falseto refuse the call. - Metrics — record method timings through Dropwizard Metrics.
- Logging — print invocation details through the project logger.
- Virtual proxy strategy — lazily create the wrapped instance only when needed.
Each is a single builder call. You can combine as many as you need on the same proxy.
A minimal example
Service proxy = DynamicProxyBuilder
.createBuilder(Service.class, new ServiceImpl())
.addIPreAction((original, method, args) -> { /* before */ })
.addIPostAction((original, method, args) -> { /* after */ })
.build();
The first argument to createBuilder is the interface type. The second is the
real implementation that the proxy will delegate to. Everything else is
optional.
What you do not do
- You do not need a classpath scanner. The proxy is created for one instance, in one place.
- You do not need a special runtime container. JDK dynamic proxies use a class loader you control.
- You do not need pointcut expressions. The hooks apply to every method on the interface.
Next steps
Read the page for each builder feature you want to use. Each one is small and self-contained.
In this section
- DynamicProxyBuilder
The fluent builder behind every runtime proxy in ProxyBuilder.
- Security rules
Block proxy invocations declaratively. If the rule returns false, the call does not reach the implementation.
- Metrics
Record method timings on a runtime proxy through Dropwizard Metrics.
- Virtual proxies
Defer creation of an expensive implementation until it is first used.