Spring Framework中ProxyFactory和ProxyFactoryBean有什么区别?

时间:2017-11-04 14:39:27

标签: java spring spring-aop

我有以下示例代码:

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");
    }
}

最后 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);
    }
}

主要方法的输出将是:

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

就这个非常小的例子而言,它们完全符合相同的目的。 ProxyFactory documentation州:

  

AOP代理的工厂用于程序化使用,而不是通过   bean工厂中的声明性设置。这个类提供了一种简单的方法   在自定义用户代码中获取和配置AOP代理实例。

但在我看来,您可以将ProxyFactoryBean用于同一目的吗?

这两个类如何用于不同的目的?

1 个答案:

答案 0 :(得分:0)

ProxyFactory独立于Spring的IoC容器。 ProxyFactoryBean将Spring AOP与Spring的IoC容器结合在一起。