My spring bean is not injected or created when I use the autowire and component annotations

前端 未结 2 1030
醉话见心
醉话见心 2021-01-24 13:36

I\'m trying to understand DI, but my spring bean is not injected or created when I use the autowire and component annotations. Instead I get a nullpointer exception because my b

相关标签:
2条回答
  • 2021-01-24 13:44

    Try to add

    <context:annotation-config/>  
    

    to your Spring config file.

    0 讨论(0)
  • 2021-01-24 13:59

    You're only creating a BeanFactory, which has extremely limited functionality. It really does nothing more than instantiate beans and let you manually wire them together. The functionality you're looking for only exists in ApplicationContexts, which is really Spring's bread and butter. Change

    BeanFactory factory = new XmlBeanFactory(
            new ClassPathResource("application-context.xml"));
    

    to

    BeanFactory factory = new ClassPathXmlApplicationContext(
            "application-context.xml");
    

    Then read "The BeanFactory" to get familiar with the distinction.

    0 讨论(0)
提交回复
热议问题