Spring @Autowired for setter methods vs non-setter methods

前端 未结 3 1733
北海茫月
北海茫月 2021-02-09 18:47

According to @Autowired javadoc:

Marks a constructor, field, setter method or config method as to be autowired by Spring\'s dependency injection facili

相关标签:
3条回答
  • 2021-02-09 19:12

    Config-method in this context refers to methods that you would specify under init-method or @PostConstruct

    Setter as you already know is like setXXX

    So obviously there is no difficulty in finding which is which. At the same time note that spring can not autowire based on parameter names.

    0 讨论(0)
  • 2021-02-09 19:16

    A config method is a factory-like method, which in this case would get the paramaters autowired:

    @Autowired
    public SomeObject initSomeObject(Object1 o1, Object2 o2, ...) {
    

    @Autowired merely ensures that Spring will (attempt to) provide the needed parameters.

    0 讨论(0)
  • 2021-02-09 19:34

    @Autowired annotation can be used with constructor, setter method or just any other method. Whenever Spring finds @Autowired annotation it will try to find beans matching to method parameters and will invoke that method. If multiple methods (setter or non-setter) have @Autowired annotation, all will be invoked by Spring after bean instantiation.

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