How does @autowired annotation works for a private field?

This question already has an answer here:

  • What is reflection and why is it useful? 20 answers
  • How does Spring @Autowired work 4 answers

  • It works with reflection. Here you can find an example of how to set public fields. But setting private fields does not make much of a difference


    @Component
    public class A(){}
    
    @Component
    public class B(){
    @Autowired
    private A a;
    }
    

    Spring create beans mentioned as @Component. here bean A will be created first and since B is dependent on A, then injection of A to B is done. there's no need for any setters. just @Component is required. Spring uses CGLib for creation of beans using reflection.


    Three types of dependency injection

    There are at least three ways an object can receive a reference to an external module:

    constructor injection: the dependencies are provided through a class constructor.

    setter injection: the client exposes a setter method that the injector uses to inject the dependency.

    interface injection: the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency.

    链接地址: http://www.djcxy.com/p/47612.html

    上一篇: 用Core JAVA编程

    下一篇: @autowired注释如何用于私人领域?