org.springframework.beans.factory.BeanCreationException:无法自动装配字段:

org.springframework.beans.factory.BeanCreationException: Could not autowire field:

我有问题:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'itemsController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.hdx.ssm.service.ItemsService com.hdx.ssm.controller.ItemsController.itemsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.hdx.ssm.service.ItemsService] 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)}

这是 ItemsController:

@Controller
@RequestMapping("/items")
public class ItemsController {
    @Autowired
    private ItemsService itemsService;

和项目服务:

  public interface ItemsService {

执行class:

public class ItemsServiceImpl implements ItemsService {
   @Autowired
   private ItemsMapperCustom itemsMapperCustom;
    @Autowired
    private ItemsMapper itemsMapper;

还有一些设置 spring-mvc.xml:

  <context:component-scan base-package="com.hdx.ssm.controller"/>

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>


    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter"/> 
            </list>
        </property>
    </bean>

我该如何解决这个问题?

您需要将 @Service 添加到您的 ItemsServiceImpl 中,以便 Spring 容器知道它是一个 Spring 托管 bean:

@Service
public class ItemsServiceImpl implements ItemsService {
    @Autowired
   private ItemsMapperCustom itemsMapperCustom;
    @Autowired
    private ItemsMapper itemsMapper;

   //other code
}