2

我们遇到了关于 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 在初始加载时初始化它的内容,并且因为 logger 在它的构造函数中,它在上下文本身的完整构造之前被初始化,因此它的属性 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. 

有没有办法解决这个问题。

提前致谢。

4

1 回答 1

0

与其在初始化时直接自动装配依赖关系,不如稍后使用@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的。

于 2013-12-17T11:25:50.927 回答