在Spring Boot中,我可以使用3种方法注入依赖项...
以下是使用每个类的类的3个基本示例。
物业注入
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;
}
}
构造函数注入
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;
}
}
我的问题是:什么是首选方法,每种方法都有利弊吗?