spring @Autowire property vs setter

前端 未结 7 1796
抹茶落季
抹茶落季 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:10

    If you can, you should avoid the setter. If you don't need it, it's better when it doesn't exists, right?

    I personally prefer Guice allowing me to write

    public class TextEditor {
       private final SpellChecker spellChecker;
    
       @Inject public TextEditor(SpellChecker spellChecker) {
          this.spellChecker = spellChecker;
       }
    
       public void spellCheck(){
          spellChecker.checkSpelling();
       }
    }
    

    This goes a step further: With a final field, I know it won't ever change and I get the multithreading visibility guarantee.

提交回复
热议问题