Spring inferred constructor

Article directory


Content summary

Instantiate

The rules for Spring to create its own beans are as follows:

  • By default, the parameterless construction method is used. If there is only one parameter, use the parameterized method. If there are multiple parameters, an error will be reported.
  • Multiple parameters, and one of them has @Autowired annotation: Use the one with @Autowired annotation, and Spring will automatically inject the parameter value. Note that @Primary/@Order/Ordered, etc. do not have this effect
  • When the class is lazy loaded or prototype scoped, you can use getBean(String name, Object... args) or BeanDefinition.getConstructorArgumentValues().addGenericArgumentValue(new XxxObject()) to manually specify the constructor. If not found, an error will be reported.
  • Let Spring automatically select the constructor method and parameter values
    • XML 时, autowire=“constructor”
    • Annotation 时, BeanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR)

Select construction method

  • By default, the parameterless constructor is used. If there is no parameterless constructor but there is another one, use this one.
  • If the constructor parameter value is specified, through getBean or BeanDefinition, then use the constructor with matching parameters.
  • Specify autowire=constructor to let Spring automatically select the constructor method and input parameter values.
  • Specify the @Autowired annotation to a certain constructor and hope that Spring will automatically find the input parameter value of the constructor.

Guess you like

Origin blog.csdn.net/mrathena/article/details/134418819