繁体   English   中英

Spring 引导 MVC - 无法在服务中自动装配存储库 class

[英]Spring boot MVC - Unable to Autowire Repository in the service class

我有服务 class 为相应的存储库定义了 @Autowired 注释

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StoreService {

    @Autowired
    private StoreRepository repository;

存储库接口定义为从 JpaReepository 扩展

import org.springframework.data.jpa.repository.JpaRepository;

public interface StoreRepository extends JpaRepository<Store, String> {
}

并且应用程序自动装配服务 Class

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@RestController
public class StoreController {

    @Autowired
    private StoreService service;

运行时出现以下错误

***************************
APPLICATION FAILED TO START
***************************

Description:

Field repository in com.mypackage.service.StoreService required a bean of type 'com.mypackage.respository.StoreRepository' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.mypackage.respository.StoreRepository' in your configuration.

我认为你应该用@Repository注释你的存储库,然后它会被 Spring Framework 自动启用。

@Repository
public interface StoreRepository extends JpaRepository<Store, String> {
}

只需将@Repository注释添加到StoreRepostiry ,它应该可以工作。

以下是 Spring 识别并可用于自动装配而无需显式将其声明为 bean 的最常用注释: @Service Service、 @Component Repository 和@Repository

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM