ProxyFactoryBean in action

We will define a regular Spring bean as target bean, say TransferService, and then, using ProxyFactoryBean, we will create a proxy that will be accessed by our application. To advice the transfer method of TransferService, we will set the point expression using AspectJExpressionPointcut and we will create the interceptor, which we will set into DefaultPointcutAdvisor to create the advisor. 

The target object or bean is as follows:

public class TransferServiceImpl implements TransferService {
private static final Logger LOGGER =
Logger.getLogger(TransferServiceImpl.class);

@Override
public boolean transfer(Account source, Account dest, Double amount) {
// transfer amount from source account to dest account
LOGGER.info("Transferring " + amount + " from " +
source.getAccountName() + "
to " + dest.getAccountName());
((TransferService)
(AopContext.currentProxy())).checkBalance(source);
return true;
}

@Override
public double checkBalance(Account a) {
return 0;
}
}

The following code is for the method interceptor or advice:

public class TransferInterceptor implements MethodBeforeAdvice{

private static final Logger LOGGER =
Logger.getLogger(TransferInterceptor.class);

@Override
public void before(Method arg0, Object[] arg1, Object arg2) throws
Throwable {
LOGGER.info("transfer intercepted");
}
}

The Spring configuration is as follows:

@Configuration
public class ProxyFactoryBeanConfig {

@Bean
public Advisor transferServiceAdvisor() {
AspectJExpressionPointcut pointcut = new
AspectJExpressionPointcut();
pointcut.setExpression("execution(*
com.packt.springhighperformance.ch03.bankingapp.service
.TransferService.checkBalance(..))");
return new DefaultPointcutAdvisor(pointcut, new
TransferInterceptor());
}

@Bean
public ProxyFactoryBean transferService(){
ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
proxyFactoryBean.setTarget(new TransferServiceImpl());
proxyFactoryBean.addAdvisor(transferServiceAdvisor());
proxyFactoryBean.setExposeProxy(true);
return proxyFactoryBean;
}
}

In the preceding code samples, we have not separately defined TransferService as Spring bean. We have created an anonymous bean of TransferService and then created its proxy using ProxyFactoryBean. This has an advantage that there will be only one object of the TransferService type and no one can obtain an unadvised object. This also reduces ambiguity if we want to wire this bean to any other bean using the Spring IoC.

With ProxyFactoryBean, we can configure AOP proxies that provide all flexibility of the programmatic method without needing our application to do AOP configurations.

It is best to use the declarative method of proxy configuration over the programmatic method unless we need to perform a manipulative action at runtime or we want to gain fine-grained control.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset