Search code examples
javainterceptorspring-aopspring-4aspect

how to set many targets to 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;
}

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


Solution

  • 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();
    }
    

    This code is untested, as I don't have an IDE with Spring (or Maven) at hand, but the gist should work.