java / expert
Snippet
Custom AOP Logic using MethodInterceptor and ProxyFactory
Direct use of ProxyFactory allows for manual AOP composition without relying on component scanning or annotations. By implementing MethodInterceptor, you gain access to the 'MethodInvocation', allowing you to wrap target calls with cross-cutting concerns like performance monitoring or security checks dynamically.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
public <T> T createSecureProxy(T target) {ProxyFactory factory = new ProxyFactory(target);factory.addAdvice((MethodInterceptor) invocation -> {long start = System.nanoTime();try {return invocation.proceed();} finally {System.out.println("Execution time: " + (System.nanoTime() - start));}});return (T) factory.getProxy();}
spring
Breakdown
1
ProxyFactory factory = new ProxyFactory(target);
Initializes a factory to create a JDK dynamic proxy or CGLIB proxy for the target object.
2
factory.addAdvice((MethodInterceptor) invocation -> { ... });
Adds an interceptor that executes logic before and after the actual method call.
3
return invocation.proceed();
Proceeds to the next interceptor in the chain or the final target method.