Sunday, June 19, 2016

Creating Static Proxy (or) Understanding Proxy

If you want to call a method then you will use the instance to invoke the method.

Caller à instance.method

If you want to add cross cutting concerns (Logging, Transaction Management,  Audit and Security) to your method then we use the proxy to invoke the method and proxy will do the cross cutting concerns.

 Caller à Proxy à instance.method

public interface IStringService {
      public String converToUpperCase(String text);
public class StringService implements IStringService {

      public String converToUpperCase(String text) {
            return text != null ? text.toUpperCase() : text;

public class StringServiceProxy implements IStringService {

      private IStringService stringService;

      public StringServiceProxy(IStringService stringService) {
            this.stringService = stringService;

      public String converToUpperCase(String text) {
            System.out.println("Before : calling the service");
            String result = stringService.converToUpperCase(text);
            System.out.println("After : calling the service");
            return result;

public class StringServiceProxyTest {
      public static void main(String[] args) {
            IStringService stringService = new StringService();
            StringServiceProxy stringServiceProxy = new StringServiceProxy(stringService);
            String name = "Lenin Kumar Koppoju";
            String upper = stringServiceProxy.converToUpperCase(name);

No comments:

Post a Comment