简体   繁体   中英

How to use Autowired annotations

I have a doubt to use autowire annotation in different scenarios...

public Class A {
  @Autowired
  public B b;

  public void print() {
    System.out.println("the value is " + b.getValue());
  }

}

Example 2:

public Class A {
  public B b;

  @Autowired
  Public A(B b){}

  public void print() {
    System.out.println("the value is " + b.getValue());
  }
}

The first method to autowire objects is called field-injection and the second one is called constructor-injection . There are many posts on SO about these two topics! Eg What exactly is Field Injection and how to avoid it? This should answer all of your questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM