【问题标题】:org.springframework.beans.factory.BeanCreationException: Could not autowire field:org.springframework.beans.factory.BeanCreationException:无法自动装配字段:
【发布时间】:2026-01-19 02:45:02
【问题描述】:

我有问题:

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;

和 ItemsService:

  public interface ItemsService {

实现类:

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>

我该如何解决这个问题?

【问题讨论】:

  • ItemsServiceImpl 是否标记为@Component@Servicecomponent-scan 也应该包含服务类的路径。
  • 我已经修改了。谢谢你的回答!@Rohan

标签: spring maven spring-mvc intellij-idea mybatis


【解决方案1】:

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

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

   //other code
}

【讨论】:

  • 谢谢你的回答!@javaguy