2013-12-17 79 views
2

我们遇到了有关Spring @Configurable注解的问题。编译时编织(AspectJ)和仪器按预期工作时,我的项目中的所有内容都正确设置。Spring @Configurable Spring Singleton bean构造函数

但问题如下。我们正在构建一些巧妙的记录器,可能会在春季范围之外初始化。因此,我们决定把它@Configurable

@Configurable 
public class Logger(){ 
    @Autowired A a; 
} 

我们想要使用Spring @Controller,这是定义无状态(单身),这里面记录仪,所以我们有:

@Controller 
public class Controller { 
    Logger l = new Logger(); 
} 

但由于控制器是singleton,那么Spring会在初始加载时初始化其内容,并且由于记录器在其构造函数中,因此它在完成上下文本身构造之前被初始化,因此其属性A永远不会被初始化。以下相当具有说明性的警告信息被打印出来:

2013.12.16 18:49:39.853 [main] DEBUG o.s.b.f.w.BeanConfigurerSupport - 
BeanFactory has not been set on BeanConfigurerSupport: 
Make sure this configurer runs in a Spring container. 
Unable to configure bean of type [Logger]. Proceeding without injection. 

有什么办法解决这个问题。

在此先感谢。

回答

0

,而不是直接在initlization自动装配依赖关系,做到这一点后使用@PostConstruct回调手动:

@Configurable 
public class Logger() { 
    @Autowired private ApplicationContext appCtx; 
    private A a; 
    @PostConstruct private void init() { 
     this.a = appCtx.getBean(A.class); 
    } 
} 

这工作,因为ApplicationContext总是首先初始化,始终可用于注射。但是,这会让您的代码意识到Spring。

更好的解决方案是不使用@Configurable,而是使用Spring管理的工厂来创建新的Logger

+0

您确定这可行吗?我目前无法验证它,但在我看来,它与我的代码存在同样的问题。 ApplicationContext不会被自动装配,因为它现在还没有准备好(上下文正在初始化,并且在构建Logger之前无法初始化,因为Logger是Controller单例bean的一部分)。因此AnnotationBeanConfigurerAspect将无法访问ApplicationContext,并且无法自动装载它。 – malejpavouk

相关问题