Spring @Configurable在Spring单例bean构造函数中

时间:2013-12-17 10:38:08

标签: spring aspectj autowired configurable

我们遇到了有关Spring @Configurable 注释的有趣问题。我的项目中的所有内容都已正确设置以进行编译时编织( AspectJ ),并且检测按预期工作。

但问题出现了。我们正在构建一些聪明的记录器,它可能在spring范围之外初始化。所以我们决定将其设为@Configurable

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

我们想在Spring @Controller中使用这个Logger,这是定义无状态的(单例),所以我们有:

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

但是因为Controller是单例,所以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. 

有没有办法摆脱这个问题。

提前致谢。

1 个答案:

答案 0 :(得分: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