Home > OS >  What is the difference between AUTOWIRING by attribute, setter and constructor
What is the difference between AUTOWIRING by attribute, setter and constructor

Time:10-16

I'm new to Spring Boot, I understand that there are 3 ways to AUTOWIRING using the @Autowired tag, which are: by attribute, by setter method and by constructor. My question is how the 3 modes differ, in what cases should I use one or the other, what advantage or quality does one have that the other does not. Look for information, but it is not clear to me, somewhere in some videos they said that the constructor method is used if you plan to do TESTING, but it is not entirely clear to me why it would be like that.

CodePudding user response:

You can absolutely use any of them and they result into exactly the same outcome. However, based on ease, readability, coding standards or better coding practices there are few differences.

Constructor-based: should be used for mandatory dependencies. In constructor, we should assign constructor args to final member fields.Constructors visually stand separate from methods.

@Component
public class ExampleClass {

private MyController myController;
private MyService myService;
private MyDao myDao;

@Autowired
public ExampleClass(MyController myController, MyService myService, MyDao myDao) {
    this.myController = myController;
    this.myService = myService;
    this.myDao = myDao;
}
//...
}

Setter-based: Should be used for optional dependencies.Takes away focus form business methods

@Component
public class ExammpleClass {
private MyController myController;
private MyService myService;
private MyDao myDao;

@Autowired
public void setController(MyController myController) {
    this.myController = myController;
}

@Autowired
public void setService(MyService myService) {
    this.myService = myService;
}

@Autowired
public void setDao(MyDao myDao) {
    this.myDao = myDao;
}
 //......
}

Field-based: Spring discourages the use of this because it would possibly hide mandatory fields from outside which would otherwise be assigned in the constructor. This would take away the advantage of properly initialized POJO, specially if intended to use outside of Spring container. It uses less boilerplate code and focus on bussiness logic.

@Component
public class ExampleClass {

@Autowired 
private MyController myController;
@Autowired 
private MyService myService;
@Autowired 
private MyDao myDao;
//....
}

When number field is more in that case field based injection perform better than constructor based and setter based injection,In perspective of less line of code and maintenance of code,But most of the developer like to use constructor based because it safe and provide immutability and its visually apart from business logic.

  • Related