Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring@Configurable-in-Spring单例bean构造函数_Spring_Aspectj_Autowired_Configurable - Fatal编程技术网

Spring@Configurable-in-Spring单例bean构造函数

Spring@Configurable-in-Spring单例bean构造函数,spring,aspectj,autowired,configurable,Spring,Aspectj,Autowired,Configurable,我们遇到了关于Spring@Configurable注释的有趣问题。我的项目中的所有内容都已正确设置为编译时编织(AspectJ),并且工具按照预期工作 但问题随之而来。我们正在构造一些聪明的记录器,它可能在spring范围之外初始化。所以我们决定让它@Configurable @Configurable public class Logger(){ @Autowired A a; } 我们希望在Spring@Controller中使用此记录器,根据定义,它是无状态的(单例),因此我们有

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

但问题随之而来。我们正在构造一些聪明的记录器,它可能在spring范围之外初始化。所以我们决定让它@Configurable

@Configurable
public class Logger(){
   @Autowired A a;
}
我们希望在Spring@Controller中使用此记录器,根据定义,它是无状态的(单例),因此我们有:

@Controller
public class Controller {
   Logger l = new Logger();
}
但因为控制器是单例的,所以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. 
有办法解决这个问题吗


提前感谢。

不要在初始化时直接自动连接依赖项,而是在以后使用
@PostConstruct
回调手动执行此操作:

@Configurable
public class Logger() {
    @Autowired private ApplicationContext appCtx;
    private A a;
    @PostConstruct private void init() {
        this.a = appCtx.getBean(A.class);
    }
}
这是因为
ApplicationContext
总是首先初始化,并且总是可用于注入。但是,这使您的代码了解Spring


更好的解决方案是不使用
@可配置的
,而是使用Spring管理的工厂来创建新的
记录器
s。

您确定这会起作用吗?我目前无法验证它,但在我看来,它与我的代码有相同的问题。ApplicationContext不会自动连接,因为它目前还没有准备好(上下文正在初始化,在构建记录器之前无法初始化,因为记录器是控制器单例bean的一部分)。因此,AnnotationBeanConfigureRespect将无法访问ApplicationContext,并且无法自动关联它。