FactoryBean咱们以前已经提到过,就是一个建立bean的工厂模式类。而ProxyFactoryBean像其它的FactoryBean实现同样,只是多引入了一个间接层,也就是代理。若是定义一个名为bwf的ProxyFactoryBean, 引用bwf的对象看到的将不是ProxyFactoryBean实例自己,而是一个ProxyFactoryBean实现里getObject() 方法所建立的对象。 这个方法将建立一个AOP代理,它包装了一个目标对象。spring
使用ProxyFactoryBean的最重要的好处之一就是建立AOP代理,这意味着通知和切入点也能够由IoC来管理。这也是实现AOP代理的重要思想。经过代理拦截对方法的调用,并调用相应的处理程序,能够实现程序逻辑的加强,而不须要改动原有代码。app
<beans>代理
<bean id="customerService" class="com.bwf.CustomerService">code
</bean>对象
<bean id="aroundAdvice" class="com.bwf.AroundMethod" />get
<bean id="customerServiceProxy"class
class="org.springframework.aop.framework.ProxyFactoryBean">aop
<property name="target" ref="customerService" />map
<property name="interceptorNames">引用
<list>
<value>customerAdvisor</value>
</list>
</property>
</bean>
<bean id="customerAdvisor"
class="org.springframework.aop.support.NameMatchMethodTutorialscutAdvisor">
<property name="mappedName" value="printName" />
<property name="advice" ref="aroundAdvice" />
</bean>
</beans>
该例中,使用ProxyFactoryBean,定义了一个代理,并指向了自定义的customerService,并为被代理类指定了拦截的方式和拦截后处理方法。
在代码中要使用customerService实例,只须要以下调用:
CustomerService cust = (CustomerService)appContext.getBean("customerServiceProxy");
而后执行相应方法时,就可以自动执行切面定义的方法。