spring @Autowire property vs setter

前端 未结 7 1810
抹茶落季
抹茶落季 2021-01-30 16:40

What is the difference between anotate @Autowired to a property or do it in the setter?

As far as I know they both have the same result, but is there any reason to use o

7条回答
  •  星月不相逢
    2021-01-30 17:16

    With @Autowired annotation, you don't need a setter method. Once your bean's constructor is done with allocating/creating the object, Spring will scan for this annotation and would inject the object instances that you annotated.

    While if you have setter and if you are still using xml config, you would explicitly set properties.

    Having said that, You could annotate your constructor and setter method with autowired annotation which i would prefer as this would give me flexibility later on to move away from Spring (although i wont do it).

提交回复
热议问题