Home > OS >  Spring Boot @Component annotation not used on interface but still bean is being provided with @Autow
Spring Boot @Component annotation not used on interface but still bean is being provided with @Autow

Time:11-23

I am a new learner of Spring Boot, As far as I learnt by now, we need to use @Component above a class/interface for spring to store the bean in 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 bean 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 @components myself but its saying that I have multiple bean of same name. I am expecting to understand the process, how the bean is being delivered without @Component annotation.

CodePudding user response:

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

  • Related