In Spring Boot I can inject dependencies using 3 methods...
- Property Injection
- Setter Injection
- Constructor Injection
Here are 3 basic examples of how classes that use each.
Property Injection
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PageController {
@Autowired
private NotificationService notificationService;
}
Setter Injection
import com.abc.foo.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PageController {
private NotificationService notificationService;
@Autowired
public void setNotificationService(NotificationService notificationService) {
this.notificationService = notificationService;
}
}
Constructor Injection
import com.abc.foo.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PageController {
private NotificationService notificationService;
@Autowired
public PageController(NotificationService notificationService) {
this.notificationService = notificationService;
}
}
My question is this: What is the preferred method and are there pros and cons to each?