How does the @Autowired interface, which extends CrudRepository, works? I would like to have some insights

后端 未结 1 619
忘了有多久
忘了有多久 2020-12-30 09:26

Suppose my interface extends CrudRepository as follows

 @Repository
    public interface EmployeeRepository extends CrudRepository 
         


        
相关标签:
1条回答
  • 2020-12-30 10:19

    Well, there is indeed already a great answer about Spring Data Repositories described in : How are Spring Data repositories actually implemented? . However, when reading your question I believe there is a bit of confusion with regards the way the @Autowired works. Let me try to give the high level sequence of the events :

    1. You place the dependency on the EmployeeRepository in your code :

      
      @Autowired 
      private EmployeeRepository employeeRepository;
      
    2. By doing step (1) you indicate to the Spring container that during its startup process it should find an instance of the class which implements EmployeeRepository and inject it into the target of the @Autowired annotation. I would like here to stress the fact that in order for the injection to work properly you should have the instance of the class implementing the required interface in the Spring container during the runtime and not during the compilation process.

    3. So now a logical questions comes in : "Where from a class implementing the UserRepository appears in the Spring container during its startup process if we have not explicitly defined that class" ?

    4. Thats were a detailed answer from Oliver comes in : How are Spring Data repositories actually implemented?. In the nutshell what happens is that Spring Data during the container bootstrap process scans for the all repositories interfaces; creates new classes (Proxies) which implement these interfaces; puts instances of those classes into the Spring container which allows for @Autowired to find and inject them as it would do for any other Spring bean within the container.

    And again, these process works only if you have Spring Data set up and correctly configured, otherwise indeed the injection would fail.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题