@Autowired不适用于CrudRepository

时间:2019-02-05 01:19:38

标签: spring-boot

我在注入存储库时遇到问题,在注入服务方面没有问题。我将回购注入服务:

  @Service
    public class AuthorService {
        @Autowired
        private AuthorRepository repository;

        public String getAll(){return "XXXXX";}
    }

,存储库为:

public interface AuthorRepository extends CrudRepository<Author, Integer> {
}

我的代码结构如下:

enter image description here 主要课程:

@SpringBootApplication
public class AuthorBookGraphqlApplication {
    public static void main(String[] args) {
        SpringApplication.run(AuthorBookGraphqlApplication.class, args);
    }
}

在启动时抛出错误:

Field repository in com.author.book.graphql.demo.service.AuthorService required a bean of type 'com.author.book.graphql.demo.repository.AuthorRepository' that could not be found.

2 个答案:

答案 0 :(得分:1)

更新代码如下

Spring会自动将bean导入容器,并使用这些注释注入依赖项。

@ Component,@ Controller,@ Service和@Repository-帮助定义bean,以便容器知道它们并可以通过@Autowired为您注入它们。

@Autowired-在此仅处理接线部分。

@Service
   public class AuthorService {

      @Autowired
       private AuthorRepository repository;

       public String getAll(){return "XXXXX";}
   }


@Repository
public interface AuthorRepository extends CrudRepository<Author, Integer> {}

答案 1 :(得分:0)

在类AuthorRepository之前,让我们添加更多注释@Repository