簡體   English   中英

Spring Boot @Component 注釋未在接口上使用,但仍由 @Autowired 提供 bean

[英]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 異常。

有關此主題的更多信息,請查看baeldung文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM