Could not autowire field in spring. why?

后端 未结 8 1791
长情又很酷
长情又很酷 2020-12-08 20:09

I keep getting this error, and can\'t figure out why.. yes I know there many people had similar issues, but reading the answers they got, does not solve my problem.

相关标签:
8条回答
  • 2020-12-08 20:40

    When you get this error some annotation is missing. I was missing @service annotation on service. When I added that annotation it worked fine for me.

    0 讨论(0)
  • 2020-12-08 20:42

    In java config,make sure you have import your config in RootConfig like this @Import(PersistenceJPAConfig.class)

    0 讨论(0)
  • 2020-12-08 20:45

    I've faced the same issue today. Turned out to be I forgot to mention @Service/@Component annotation for my service implementation file, for which spring is not able autowire and failing to create the bean.

    0 讨论(0)
  • 2020-12-08 20:47

    In spring servlet .xml :

    <context:component-scan base-package="net.controller" />
    

    (I assumed that the service impl is in the same package as the service interface "net.service")

    I think you have to add the package net.service (or all of net) to the component scan. Currently spring only searches in net.controller for components and as your service impl is in net.service, it will not be instantiated by spring.

    0 讨论(0)
  • 2020-12-08 20:48

    for those who are facing the same problem, even if you added component-scan on your XML and still facing the same issue please Make Sure you wrote a clean code in your Repository. the problem you are facing is directly related to the code you wrote for hibernate transaction. most Importantly please make sure your db Query is correct.

    0 讨论(0)
  • 2020-12-08 20:49

    Well there's a problem with the creation of the ContactServiceImpl bean. First, make sure that the class is actually instantiated by debugging the no-args constructor when the Spring context is initiated and when an instance of ContactController is created.

    If the ContactServiceImpl is actually instantiated by the Spring context, but it's simply not matched against your @Autowire annotation, try being more explicit in your annotation injection. Here's a guy dealing with a similar problem as yours and giving some possible solutions:

    http://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/

    If you ask me, I think you'll be ok if you replace

    @Autowired
    private ContactService contactService;
    

    with:

    @Resource
    @Qualifier("contactService")
    private ContactService contactService;
    
    0 讨论(0)
提交回复
热议问题