简体   繁体   English

Spring3的@Configuration不能@Inject组件扫描的bean

[英]Spring3's @Configuration cannot @Inject component-scanned beans

This is my app.xml : 这是我的app.xml:

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

And there is a Dao (interface) , and DaoImpl (annotated with @Repository ) inside destiny.web package. 并有一个Dao (接口),和DaoImpl (带有加注解的@Repository )destiny.web封装内。

There is another Spring3's destiny.web.AppConfig class : 还有另一个Spring3的destiny.web.AppConfig类:

@Configuration
public class AppConfig
{
  @Inject
  private Dao daoImpl

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

It prints 'null' , why ? 它打印'null',为什么?

I am sure all these beans/configuration/repositories are scanned. 我确信所有这些bean /配置/存储库都会被扫描。 But it seems @Configuration doesn't know other scanned beans . 但似乎@Configuration不知道其他扫描的bean。 Did I miss anything ? 我错过了什么吗?

I try to solve it by @ImportResource : 我尝试通过@ImportResource来解决它:

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

But it seems causing cyclic bean scan and throws this exception : 但它似乎导致循环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]

How to solve it ? 怎么解决?

Thanks. 谢谢。

Spring will invoke constructor firstly before inject / autowiring the other component. before inject / autowiring另一个组件before inject / autowiring Spring将invoke constructor firstly therefore your dao is null while you print at the constructor, because the dao still not injected yet . 因此,当您在构造函数中打印时,您的dao为null,因为dao still not injected yet

Have a try to create test application for your configapp. 尝试为您的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");
    }
}

你有没有使用@Autowired注释而不是@Inject尝试它?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM