@Autowired instructions

Injection sequence

@Autowired first type to be injected, and then to inject names, but the names were @Resource injection, it is not recommended.

Specify the name

@Autowired may encounter problems with multiple inheritance classes, it is recommended to bring a @Qualifier designated under the name.

Use

Not recommended for use in the field, perhaps because uninitialized and reported a null pointer, it is proposed in the setter or constructor.

The initialization sequence

Java initialization order: a static variable or a static block of statements> initialize instance variables or block of statements> Constructor> @Autowired

Officially recommended wording

  • Constructor injection
@RestController
public class PersonController {

    private final PersonService personService;

   /**
     * Spring Team建议:“始终在bean中使用基于构造函数的依赖注入。始终使用断言来强制依赖”。
     */
    @Autowired
    public PersonController(@Qualifier("personService") PersonService personService){
        Assert.notNull(personService, "personService must not be null");
        this.personService = personService;
    }
}
  • set injection
@RestController
public class PersonController {

    private PersonService personService;

    @Autowired
    @Qualifier("personService")
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }
}

Guess you like

Origin www.cnblogs.com/liehen2046/p/11058386.html