【问题标题】:Spring3's @Configuration cannot @Inject component-scanned beansSpring3 的@Configuration 不能@Inject 组件扫描的bean
【发布时间】:2011-04-16 01:37:40
【问题描述】:

这是我的 app.xml:

<context:component-scan base-package="destiny.web" />
<context:annotation-config/>

并且有一个 Dao(interface) 和 DaoImpl(用 @Repository 注释)在命运.web 包中。

还有另一个Spring3的命运.web.AppConfig类:

@Configuration
public class AppConfig
{
  @Inject
  private Dao daoImpl

  public AppConfig()
  {
    System.out.println("dao = " + daoImpl);
  }
}

它打印 'null' ,为什么?

我确信所有这些 bean/配置/存储库都已被扫描。但似乎 @Configuration 不知道其他扫描的 bean 。我错过了什么吗?

我尝试通过@ImportResource 解决它:

@Configuration
@ImportResource("classpath:app.xml")
public class AppConfig

但它似乎导致循环 bean 扫描并抛出此异常:

{main} org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Only one AsyncAnnotationBeanPostProcessor may exist within the context.
Offending resource: class path resource [app.xml]

如何解决?

谢谢。

【问题讨论】:

    标签: spring configuration dependency-injection spring-3


    【解决方案1】:

    Spring 将 invoke constructor firstly before inject / autowiring 其他组件。因此,当您在构造函数中打印时,您的 dao 为空,因为 dao still not injected yet.

    尝试为您的 configapp 创建测试应用程序。

    public class Main {
        public static void main(String[] args) {
            ApplicationContext context =
                new ClassPathXmlApplicationContext("stackoverflow.xml");
    
            AppConfig appConfig = context.getBean(AppConfig.class);
            appConfig.getConfig("smtp.host");
        }
    }
    

    【讨论】:

      【解决方案2】:

      您是否也尝试过使用注释@Autowired 而不是@Inject

      【讨论】:

      • 我不得不将 bean 配置从 @Configuration 文件移出到 applicationContext.xml,但我仍然有其他 bean 在 @Configuration 文件中引用它。通过使用这里给出的@Autowired 建议,我能够成功地绕过这个问题。这是一个很好的答案/建议。
      猜你喜欢
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-21
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多