BeanNameAutoProxyCreator与导入配置之间的隐式依赖关系

时间:2013-08-23 20:31:56

标签: spring spring-aop

在我的公司,我们正在研究面向方面的跟踪拦截器,类似于DebugInterceptor。我们正在配置CustomizableTraceInterceptor并使用BeanNameAutoProxyCreator为AOP自动代理bean。

我们面临的问题是,当我们在配置中引入BeanNameAutoProxyCreator时:

@Configuration
@Import(BConfig.class)
@EnableAspectJAutoProxy
public class AConfig {
    @Bean
    public static BeanNameAutoProxyCreator beanNameAutoProxyCreator() {
        BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator();
        beanNameAutoProxyCreator.setInterceptorNames(new String[] {DEBUG_INTERCEPTOR_NAME});
        beanNameAutoProxyCreator.setBeanNames(new String[] {BEANS_NAMES_EXPRESSION});
        return beanNameAutoProxyCreator;
    }
}

我们得到一个org.springframework.beans.factory.NoSuchBeanDefinitionException:没有类型[X]的限定bean,其中X是Resteasy Proxy。此Resteasy代理在BConfig中声明。

现在,如果我将Resteasy Proxy bean配置移到AConfig,这个问题就解决了,@DependsOn也解决了这个问题。

我的问题是3:什么时候Spring能够解决bean之间的依赖关系?为什么使用BeanNameAutoProxyCreator会更改此行为?解决此问题的推荐方法是什么(BeanPostProcessor,@ DependsOn等)。

1 个答案:

答案 0 :(得分:1)

静态BeanNameAutoProxyCreator取决于普通bean(可能是由于BEANS_NAMES_EXPRESSION)。因为它是静态的,所以在任何其他bean之前加载/引导它,特别是在bean处理@Import之前。所以基本上在分析要处理的bean时,BConfig尚未加载。这就是为什么当你将bean移动到AConfig或者这个bean的依赖时它可以工作的原因。

我可能会恢复使用BeanNameAutoProxyCreator并依赖@EnableAspectJAutoProxy和使用bean pointcut的方面来附加所需的拦截器。

由于2种不同的AOP策略/机制,在BeanNameAutoProxyCreator旁边引入@EnableAspectJAutoProxy还可能导致代理被创建,这也是另一种风险。