Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)

来源:互联网 发布:苍蝇水在淘宝怎么买 编辑:程序博客网 时间:2024/05/16 07:08

在项目启动中出现这个报错,让我感到困惑,经过我一番捣腾终于知道是啥原因,下面解释一下为什么会出现这样的错误:

<span style="font-size:12px;">org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'orderInfoUCMPController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.sf.egmas.dcn.web.service.orderInfo.OrderInfoUCMPService com.sf.egmas.dcn.web.controller.orderInfo.OrderInfoUCMPController.orderInfoUCMPService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'OrderInfoUCMPService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.sf.egmas.dcn.web.utils.UcmpUtil com.sf.egmas.dcn.web.service.orderInfo.impl.OrderInfoUCMPServiceImpl.ucmpUtil; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:No matching bean of type [com.sf.egmas.dcn.web.utils.UcmpUtil] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}</span>

Autowired 根据类型去spring容器找,找不到那个类,就会报错,这是引起这个错误的原因;

下面普及一下这个注解:

@Autowired(required=false)当根据类型去找,找不到时,注入一个空。
@Autowired(required=true)当根据类型去找,找不到时,抛出异常信息

@component(把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>)

这里有两种解决方案:

第一种:使用@Autowired(required=false),但是这样会有一个问题,虽然不会报错了,但是在使用的时候调用不到里面的方法(不建议);

第二种:使用@Component泛指组件,当组件不好标记的时候,可以用这个注解来标注;

如果不使用@component 来标注,你使用注入的时候,肯定在spring容器中找不到相应的bean;

示例:

<span style="font-size:14px;">@Componentpublic class UcmpUtil {}</span>


我今天在网上看了下,报这种错误的人挺多的,但是没有人说使用这个注解来标注;

我希望会有更多人看到我这篇文章,嘿嘿。。







0 0