Search code examples
javaspringspring-aop

What is the difference between ProxyFactory and ProxyFactoryBean in Spring Framework?


I have the following sample code:

MyMethodBeforeAdviceImpl.java

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class MyMethodBeforeAdviceImpl implements MethodBeforeAdvice {
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("MyMethodBeforeAdviceImpl#before");
    }
}

MyService.java

public interface MyService {
    void serve();
}

MyServiceImpl.java

public class MyServiceImpl implements MyService {
    @Override
    public void serve() {
        System.out.println("MyServiceImpl#serve");
    }
}

and finally App.java

import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.framework.ProxyFactoryBean;

public class App {
    public static void main(String[] args) {
        final MyServiceImpl myService = new MyServiceImpl();
        final MethodBeforeAdvice myMethodBeforeAdvice = new MyMethodBeforeAdviceImpl();

        final ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.addAdvice(myMethodBeforeAdvice);
        proxyFactory.setTarget(myService);

        MyService proxyServiceFromFactory = (MyService) proxyFactory.getProxy();
        proxyServiceFromFactory.serve();

        final ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
        proxyFactoryBean.addAdvice(myMethodBeforeAdvice);
        proxyFactoryBean.setTarget(myService);

        MyService proxyServiceFromFactoryBean = (MyService) proxyFactoryBean.getObject();
        proxyServiceFromFactoryBean.serve();

        System.exit(-1);
    }
}

The output of the main method will be:

MyMethodBeforeAdviceImpl#before
MyServiceImpl#serve
MyMethodBeforeAdviceImpl#before
MyServiceImpl#serve

So as far as for this very small example, they exactly serve the same purpose. The ProxyFactory documentation states:

Factory for AOP proxies for programmatic use, rather than via declarative setup in a bean factory. This class provides a simple way of obtaining and configuring AOP proxy instances in custom user code.

But it seems to me like you may as well use ProxyFactoryBean for the same purpose?

How do these 2 classes serve different purposes?


Solution

  • ProxyFactory is independently of Spring's IoC container. ProxyFactoryBean is combining Spring AOP with Spring's IoC container.