【问题标题】:Using a bean from the abstract configuration class in a configuration class imported in the class implementing the abstract one在实现抽象的类中导入的配置类中使用抽象配置类中的 bean
【发布时间】:2018-06-27 05:35:27
【问题描述】:

我有一个由 Impl

实现的抽象配置类 Abs

Abs有一个豆子ImportantBean

我们导入 Imprt 配置。类到 Impl 并且我需要在 Imprt

中使用 ImportantBean

我该怎么做?

IntelliJ 说它不能自动装配

类似:

@Configuration 
@Import(Imprt.class)
public class Impl extends Abs {}

@Configuration
public abstract class Abs{
  @Bean
  public ImportantBean importantBean(){
  return new ImportantBean();}
}

@Configuration
public class Imprt{
  @Autowired
  private ImportantBean importantBean;
}

【问题讨论】:

  • 有代码可以看吗?
  • 抱歉,我无法发布确切的代码。我会写一些示例
  • 您能否将其添加到问题中?
  • 这应该可以。请创建一个 minimal reproducible example 证明它失败了。
  • 一个抽象的配置类对我来说没有多大意义,你不能有多个实现,因为你只能声明一次bean。请解释你为什么需要这个?

标签: java spring configuration autowired


【解决方案1】:
@Configuration 
@Import(Imprt.class)
public class Impl extends Abs {}

@Configuration
public abstract class Abs{
  @Bean
  public ImportantBean importantBean(){
  return new ImportantBean();}
}


public class Imprt{
  @Autowired
  private ImportantBean importantBean;
}

尝试删除Imprt 类中的@Configuration。我不知道 Imprt 是做什么的,但如果不是配置,请执行此操作。

【讨论】:

    【解决方案2】:

    我认为那是因为您将重要的 Bean 创建为私有的。

    如果您在 Impl 类中添加新的 @AutowiredimportantBean,它将起作用,尽管 IntelliJ 会将其标记为错误。

    我不确定,但我认为将私有更改为受保护也应该有效。

    【讨论】:

      【解决方案3】:

      您的Imprt 配置类在自动装配时不知道从哪里获取ImportantBean。您也无法确保在构建应用程序上下文并将 bean 加载到 Spring 容器中时(我假设您使用的是 Spring 框架)ImportantBean 应该在构建之前已经存在 Imprt p>

      对于配置类Imprt接收ImportantBean

      你需要@Import Impl class to Imprt,代码应该如下图所示实现-

      @Configuration
      // @Import(Imprt.class) --> removed this
      public class Impl extends Abs {}
      
      @Configuration
      public abstract class Abs{
        @Bean
        public ImportantBean importantBean(){
        return new ImportantBean();}
      }
      
      @Configuration
      @Import(Impl.class) // ---> added new import here
      public class Imprt{
        @Autowired
        private ImportantBean importantBean;
      }
      

      【讨论】:

      • 上下文由 Impl 初始化,如果我使用您的解决方案,应用程序中将没有 Imprt 信息
      • @Vitalie 为什么不用Imprt.class 初始化上下文?导入信息是什么意思?您的 Imprt.class 具有所有配置,可以初始化导入到您的应用程序的所有其他配置。
      【解决方案4】:

      一切正常github.com/vitalieb/springContexts 问题在于 Intellij 不了解将哪个上下文配置用作主要配置。 所以唯一要做的就是在 Intellij 中添加正确的上下文作为主要上下文。

      【讨论】:

      • 这是否意味着每个克隆您的代码库的人都必须明确地进行此设置?
      • 代码在没有设置的情况下也可以工作 - 但如果你添加这个设置 IntelliJ 将不会显示错误
      猜你喜欢
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 2016-03-12
      相关资源
      最近更新 更多