0

I'm just learning Spring for about 2 weeks now and try to understand a Repository concept, so I'm still unfamiliar with many terms, but I'll try my best to explain , assuming I have class :

Product.java

  class Product {
    ...
    ...
    }

Interface ProductRepository.java

public interface ProductRepository {
    public List<Product> getAllProducts();
}

InMemoryProductRepository.java

@Repository
class InMemoryProductRepository implements ProductRepository{
....
....
}

productController.java

class productController{

  @Autowired
    private ProductRepository productRepository;


 @RequestMapping("/products")
    public String list(Model model) {


        model.addAttribute("products", productRepository.getAllProducts());
        return "products";

    }

}

In my productController is what i'm talking about,

productRepository is not directly implemented to specific object like productRepository = new InMemoryProductRepository (); , instead of the productRepository is marked with @Autowired and because InMemoryProductRepository has @Repository so InMemoryProductRepository will be injected to this productRepository reference , but my question is if there is another class who implements this ProductRepository interface and marked with @Repository also : assuming like

InMemoryProductRepository2.java

@Repository
        class InMemoryProductRepository2 implements ProductRepository{
        ....
       ....
    }

then which one of those two objects will be injected to

@Autowired
    private ProductRepository productRepository;

? How do I differ them?

Thanks , sorry for my language.

  • You want to use `@Qualifier` when injecting your repository. Take a look at the answer here, it might help you out with the autowiring concept: http://stackoverflow.com/a/19419296/1458983 – woemler Aug 21 '15 at 15:25

1 Answers1

1

If there was such scenario, you would give name to each of your implementing bean @Repository("name") and use @Qualifier("name") annotation with @Autowired.

John
  • 5,189
  • 2
  • 38
  • 62