如何为ProxyFactoryBean设置许多目标? [英] how to set many targets to ProxyFactoryBean?
问题描述
我正在使用Spring 4 AOP,现在,我将ProxyFactoryBean配置如下:
I am working with Spring 4 AOP and right now, i have my ProxyFactoryBean configured like this:
@Bean
@Primary
public ProxyFactoryBean proxyFactoryBean() {
ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
proxyFactoryBean.setTarget(new ClientService());
proxyFactoryBean.addAdvice(new LoggingAdvice());
proxyFactoryBean.addAdvice(new DebugInterceptor());
return proxyFactoryBean;
}
这有效,但是目标只是ClientService对象.
This works, but the target is just the ClientService object.
是否可以设置许多目标,而不仅仅是一个?如果可能的话,我想将这些建议设置在整个程序包中.否则,设置具体目标,但不仅要设置一个.你怎么能做到这一点 ?预先感谢
Is it possible to set many targets and not just one ? I want to set those advices to an entire package, if it is possible. Otherwise, set specifics targets, but again, not just one. How could you do that ? Thanks in advance
推荐答案
使用Spring的 AbstractAutoProxyCreator子类化这样我就可以用Java代码表示切入点.
Proxying all beans in an application context that match certain criteria is easiest done with Spring's AutoProxy-Facility. Alas, the pointcut api is somewhat cumbersome to use in java based config; I usually subclass the AbstractAutoProxyCreator so I can express the pointcut in java code.
例如,我会做类似的事情:
For instance, I'd do something like:
@Bean
AbstractAutoProxyCreator autoProxyCreator() {
return new AbstractAutoProxyCreator() {
@Override
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource customTargetSource) {
if (BusinessService.class.isAssignableFrom(beanClass)) {
return new Object[] {loggingAdvice()};
} else {
return DO_NOT_PROXY;
}
}
};
}
@Bean
LoggingAdvice loggingAdvice() {
return new LoggingAdvice();
}
@Bean
public PersonService personService() {
return new PersonService();
}
此代码未经测试,因为我手头没有带有Spring(或Maven)的IDE,但是要旨应该可以.
This code is untested, as I don't have an IDE with Spring (or Maven) at hand, but the gist should work.
这篇关于如何为ProxyFactoryBean设置许多目标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!