Search code examples
javaspringspring-bootspring-data-jpaspring-annotations

Spring Boot @Component annotation not used on interface but still bean is being provided with @Autowired


I am a new learner of Spring Boot. As far as I learned by now, we need to use @Component above a class/interface for Spring to store the bean in the Spring container. And we can inject that bean by using @Autowired. I've been working on a demo project where I can't see @Component on an interface but somehow the bean of that interface is being provided correctly. If I add @Component it says multiple beans found.

Post 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);
    }

}

The Post Repository Interface:

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>{}

No Class implemented Post Repository.

I tried adding @Component myself but it's saying that I have multiple beans of the same name. I am trying to understand the process, and how the bean is being delivered without @Component annotation.


Solution

  • Spring boot uses @EnableJpaRepositories which all interfaces/classes that extend/implement a spring data repository. In turn spring then provides an implementation which is added to the container.

    As MongoRepository is spring JPA repository, the extending interfaces are being picked up and provided as autowireable dependencies. So when you annotate your PostRepository with @Component it is picked up twice by spring, causing the multiple beans found exception.

    For more info on this topic check baeldung and docs