Spring Boot @Autowired Pros&缺点

时间:2015-10-24 15:23:40

标签: java spring spring-mvc dependency-injection spring-boot

在Spring Boot中,我可以使用3种方法注入依赖项...

  1. 物业注入
  2. Setter Injection
  3. 构造函数注入
  4. 以下是使用每个类的类的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;
        }
    
    }
    

    我的问题是:什么是首选方法,每种方法都有利弊吗?

0 个答案:

没有答案