Sitemap
J

J

Java Proxy and Spring AOP

2 min readAug 3, 2023

design patterns and proxy

proxy design pattern refers to a pattern that provides a surrogate or placeholder for another object to control access to it. Proxy pattern is often confused with decorator pattern. Decorator pattern is different in that its purpose is not to control access to the original object.

Both patterns are in compliance with OCP principle. A decorating class or an acess-controlling class have a target class in them to delegate original jobs (composition). New jobs are done by adding new code in the decorating class or the proxy. The decorator and the proxy are of the same type as the target class (by implementing the same interface), so client code can stay the same when extending the target’s behavior.

An object that extends behavior and control access of a target using the above two design patterns is called proxy.

problem

Transaction management and logging are good application areas for proxy. It is possible to add new behaviors(apply transaction or logging) to targets without modifying existing code.

However, when the application size is large and the new logic is needed in many places, too many duplicate lines and objects will be created.

Get J’s stories in your inbox

Join Medium for free to get updates from this writer.

There will be a need to create proxy of as many as the number of total target classes. Plus, the same code for new behaviors will repeat and repeat. This is not only error-prone but also exhausting. Maintenance will become a nightmare.

OOP alone is not enought to deal with cross-cutting concerns.

Spring AOP(Aspect Oriented Programming)

AOP concept can solve this problem through separating cross-cutting concerns from the main business logic and making them into reusable modules (modularization). Spring provides a proxy-based AOP. Let’s take a look at how Spring AOP solves the problem :

  • Proxy creation is automated by Spring’s proxy factories so programmers don’t need to manually create them one by one.
  • The new logic (Advice) is not depedent on any target so it can be used by multiple targets. Advice’s invoke method will take MethodInvocation callback object to avoid dependency to a specific target.
  • Where the target-independent new logic(advice) has to be applied is defined in pointcuts. Proxy factory will automatically generate proxies for targets selected by pointcuts. AutoProxyCreators provided by Spring creates a proxy with many advisors(pointcut+ advice) in it. Join points are limited to method execution because Spring’s AOP is proxy-based.

With Spring AOP, programmers can apply cross-cutting logic by simply creating Advice, Pointcuts and some configuration code. This significantly improves code reuse and maintainability compared to when only OOP is used. AOP complements OOP.

--

--