spring @Autowire property vs setter

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

    There are 3 types of autowiring:

    • Property based
    @Autowired
    private MyService service;
    
    • Constructor based. Note in Spring Boot you don't even need @Autowired annotation in this case:
    class MyController {
     private final MyService service;
    
     public MyController(MyService service) {
      this.service = service;
     }
    }
    
    • Setter based:
    private MyService service;
    
    
    @Autowired
    public void setService(MyService service) {
     this.service = service;
    }
    

    It is recommended to use Constructor based, then if not possible, Setter based and lastly Property based.

    Why?

    • First, because in Constructor based you don't even use any Spring annotations. This helps you transition to different frameworks.

    • Second, Constructor or Setter based, make unit testing much easier. You don't need to use any Spring specific testing tools and you can only use Junit and Mockito.

    • Third, Constructor based is good because you can declare the property as final and not expose setters which helps with immutability and thread safety of the class.

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