![](/img/trans.png)
[英]spring boot - integration test autowired interface no such bean found
[英]Spring Boot @Component annotation not used on interface but still bean is being provided with @Autowired
我是Spring Boot的新手。 據我所知,我們需要在 Spring 的類/接口上方使用@Component
來將 bean 存儲在 Spring 容器中。 我們可以使用@Autowired
注入那個 bean。 我一直在做一個演示項目,我在接口上看不到@Component
但不知何故正確提供了該接口的 bean。 如果我添加@Component
它說找到了多個 bean。
郵寄 Controller Class:
package com.ashik.jobmarket.controller;
import com.ashik.jobmarket.repository.PostRepository;
import com.ashik.jobmarket.model.Post;
import com.ashik.jobmarket.repository.SearchRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin(origins = "http://localhost:3000")
public class PostController {
@Autowired
PostRepository repo;
@Autowired
SearchRepository srepo;
@GetMapping("/allPosts")
@CrossOrigin
public List<Post> getAllPosts(){
return repo.findAll();
}
@GetMapping("/posts/{text}")
@CrossOrigin
public List<Post> search(@PathVariable String text){
return srepo.findByText(text);
}
@PostMapping("/post")
@CrossOrigin
public Post addPost(@RequestBody Post post){
return repo.save(post);
}
}
帖子存儲庫界面:
package com.ashik.jobmarket.repository;
import com.ashik.jobmarket.model.Post;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface PostRepository extends MongoRepository<Post, String>{}
沒有 Class 實現了 Post Repository。
我嘗試自己添加@Component
但它說我有多個同名的 bean。 我試圖了解這個過程,以及如何在沒有@Component
注釋的情況下交付 bean。
Spring 引導使用@EnableJpaRepositories
擴展/實現 spring 數據存儲庫的所有接口/類。 反過來 spring 然后提供一個添加到容器中的實現。
由於MongoRepository是 spring JPA 存儲庫,擴展接口被拾取並作為可自動裝配的依賴項提供。 因此,當您使用@Component
注釋您的PostRepository
時,它會被 spring 拾取兩次,從而導致 multiple beans found 異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.