0

In Spring Boot I can inject dependencies using 3 methods...

  1. Property Injection
  2. Setter Injection
  3. 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?

Dan Vega
  • 1,097
  • 1
  • 14
  • 23
  • I am sorry I was looking for questions regarding the property injection and that is why I didn't find it. When I use the property injection is it just creating a setter behind the scenes for me? or is this just voodoo magic :) – Dan Vega Oct 24 '15 at 15:42
  • It sets the value of the field directly using reflection. Generally speaking, it's to be avoided as it makes testing difficult. – Andy Wilkinson Oct 24 '15 at 15:55
  • Thanks @AndyWilkinson ... that is exactly what i was in search of. Appreciate the help. – Dan Vega Oct 24 '15 at 16:02

0 Answers0