Spring 控制反轉和依賴注入

自從用了Spring,就一直再說控制反轉(Inversion of Control)和依賴注入(dependency injection)。到底什麼是控制反轉,什麼是依賴注入呢?

我的理解是:控制反轉就是把Bean的創建權交給了Spring容器,由Spring容器去new對象,而不是我們手動去new對象。依賴注入就是當一個Bean需要另一個Bean的時候,通過一種解耦或是鬆耦合的方式從Spring容器中拿到Bean並組合成功能更強大,更豐富的Bean。

Spring加載Bean的三個主要步驟:定位、加載、註冊

  • 定位:找到配置Bean的地方,以前都是配置在xml文件中,現在都是通過註解的方式。
  • 加載:解析xml文件,包括Bean信息和Bean之間的依賴關係
  • 註冊:解析出來的Bean註冊到容器中,也就是註冊到IOC容器中
package com.gaohx.springbootdocker.web;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

@ComponentScan(basePackages = "com.gaohx.springbootdocker.web")
public class MySpringApplication {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MySpringApplication.class);
        DemoController demoController = context.getBean(DemoController.class);
        demoController.hello();
        context.close();
    }
}

@Controller
class DemoController{
    private DemoService demoService;
    public DemoController(DemoService demoService){
        this.demoService = demoService;
    }
    public void hello(){
        demoService.hello();
    }
}

@Service
class DemoService{
    public void hello(){
        System.out.println("hello");
    }
}

啓動Main方法,看控制檯,會有如下日誌輸出

Creating shared instance of singleton bean 'mySpringApplication'
Creating shared instance of singleton bean 'demoController'
Creating shared instance of singleton bean 'demoService'
Autowiring by type from bean name 'demoController' via constructor to bean named 'demoService'

Spring啓動的時候,會自動創建我們定義好的Bean,並自動注入Bean之間的依賴關係。當Spring啓動成功,所有Bean和Bean之間的依賴關係都已創建成功。我們不再需要關心Bean的生命週期及它們之間複雜的依賴關係。完全由容器處理。

想想如果手動維護這些Bean和Bean之間的依賴關係,那將是多麼恐怖的事情。

以上只是對Spring簡單的理解。以後有心得了再補充。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章