首頁 Java java教程 Spring Boot 中的依賴注入:幕後嚮導

Spring Boot 中的依賴注入:幕後嚮導

Sep 19, 2024 am 02:19 AM

Dependency Injection in Spring Boot: The Wizard Behind the Curtain

Spring Boot 中的依賴注入:幕後嚮導

是否曾經感覺 Spring Boot 是個神奇的管家,不知怎的,它知道你需要什麼,然後把它放在銀盤上送給你?這基本上就是依賴注入 (DI)。您可能已經使用過 DI 一百次,卻沒有停下來想:Spring 到底是如何知道注入什麼以及何時注入的?

如果這聽起來像你,歡迎加入!我們將進行一次有趣的幕後之旅,了解 Spring Boot 的 DI 如何發揮其魔力,從它如何管理 bean、@Autowired 和 bean 生命週期(從誕生到銷毀)開始。在本部落格結束時,您將像專業人士一樣展示您新發現的 DI 知識。


什麼是依賴注入?為什麼要關心?

通俗地說,依賴注入就像是讓雜貨送貨上門,而不是自己出去買。它是將「注入」依賴項(bean)的責任委託給 Spring,這樣您就不必手動建立物件或擔心它們的生命週期。

假設您是一名廚師,經營著一個繁忙的廚房(您的應用程式)。你沒有時間每次需要雞蛋、牛奶和糖時都跑出去買。如果有人(例如 Spring)能夠神奇地在您需要的時候準確地交付您需要的一切,那不是很棒嗎?

這正是 Spring DI 所做的:它找到您需要的所有成分(bean)並將它們注入到您的程式碼中,而無需您費力。很整潔,對吧?


Spring Container 的魔力:您的私人管家

好的,這就是奇蹟發生的地方。當您使用 SpringApplication.run() 執行 Spring Boot 應用程式時,Spring 會引導 ApplicationContext - 將其視為您的管家的說明手冊。它確切地知道要獲取什麼以及何時獲取。

讓我們一步一步分解:

  1. 容器初始化: 當您點選 SpringApplication.run() 時,Spring 容器(又稱 ApplicationContext)就會啟動。這就像打開虛擬餐廳的大門,一切準備就緒。

  2. Bean 建立: 容器會掃描您的程式碼以尋找 @Component、@Service、@Repository 或 @Controller 等註解。其中每一個都成為一個 bean——一個由 Spring 管理的物件。將它們視為廚房中的必備成分:麵粉、糖、雞蛋等。

  3. BeanFactory 來救援: Spring Boot 使用 BeanFactory 來建立和管理這些 Bean。這家工廠確切地知道如何以及何時創建您的 Bean,確保它們在需要時可用。

  4. 依賴注入:一旦bean準備好,Spring就會將它們注入到你用@Autowired標記的任何地方。這就像咖啡師不只會煮咖啡,還會將咖啡送到需要的地方。您甚至不必考慮 - 一切都會出現


@Autowired 如何運作?豆子大偵探福爾摩斯

啊,很好的 @Autowired 註解。有沒有想過 Spring 如何神奇地知道在哪裡注入依賴項?它有點像一個偵探,將您的需求與註冊表中正確的 bean 相匹配。

工作原理如下:

  • 類型匹配:當Spring看到@Autowired時,它會在容器中尋找相同類型的bean。想像一下,您訂購了咖啡豆(一個 CoffeeService 類),Spring 會在其 Bean 存儲庫中查找並說:“啊,我已經有了這些!讓我給你注射。”

  • 限定符:但是如果您有多個相同類型的 Bean 該怎麼辦?在這種情況下,Spring 可能會崩潰並拋出“NoUniqueBeanDefinitionException”之類的異常。但別擔心——你可以透過使用 @Qualifier 指定要注入哪個 bean 來讓 Spring 平靜下來:

@Autowired
@Qualifier("espressoBean")
private CoffeeService coffeeService;
登入後複製
  • 建構函式註入(最好的方法):如今,建構函式註入是最酷的東西。它不僅使您的 Bean 不可變,而且還使測試變得輕而易舉。操作方法如下:
public class CoffeeShop {

    private final CoffeeService coffeeService;

    @Autowired
    public CoffeeShop(CoffeeService coffeeService) {
        this.coffeeService = coffeeService;
    }
}
登入後複製

Spring 繼續自動駕駛,將 bean 注入到建構函式中,瞧,一切順利!


The Lifecycle of a Spring Bean: From Birth to Retirement Party

Beans in Spring Boot aren’t just objects. They have full-fledged lives, complete with an origin story, a fulfilling career, and an eventual retirement. Let’s follow the lifecycle of a bean:

  1. Instantiation (Birth): First, Spring creates an instance of the bean. This is like the bean’s birth. Spring goes, "Here you go, little guy!" and passes it into the container.

  2. Dependency Injection: After creating the bean, Spring populates it with dependencies (like ingredients in a cake recipe). This is where @Autowired comes into play. Your bean gets everything it needs to work properly.

  3. Post-Initialization: If you have methods annotated with @PostConstruct, Spring calls those after it injects the dependencies. It’s like giving the bean a fresh coat of paint before it goes to work.

  4. Ready for Action: Now your bean is alive and kicking. It’s ready to take on the world!

  5. Pre-Destruction (Retirement): When the application shuts down, Spring calls @PreDestroy methods to give the bean a graceful exit. This is the bean's retirement party, where it cleans up its resources.

  6. Bean Destruction: Finally, the bean is destroyed. Time to rest in peace.

Here’s how you can track these lifecycle events in code:

@Component
public class CoffeeBean {

    @PostConstruct
    public void onStart() {
        System.out.println("Bean is ready to brew some coffee!");
    }

    @PreDestroy
    public void onEnd() {
        System.out.println("Bean is retiring. Goodbye, world!");
    }
}
登入後複製

Bean Scopes: How Long Does the Magic Last?

Not all beans have the same life expectancy. Spring Boot allows you to define different scopes for beans—basically how long they live. The two most common ones are:

  • Singleton (the Default): There’s only one instance of the bean, shared across the entire application. It’s like having one espresso machine for the whole coffee shop.

  • Prototype: A new instance of the bean is created every time it’s needed. Imagine having a fresh espresso machine for every single order. It’s resource-heavy, but sometimes necessary.

@Component
@Scope("prototype")
public class LatteMachine {
    // This bean is made fresh for every use
}
登入後複製

SpringApplication.run(): The Grandmaster of DI

Alright, let’s talk about what happens when you run your Spring Boot app using SpringApplication.run(). This method is the grandmaster that kicks off the whole DI process.

  1. Start the Application Context: Spring fires up the ApplicationContext, where all beans live.
  2. Scan for Beans: Spring scans your code for beans and registers them.
  3. Inject Dependencies: Once the beans are ready, Spring starts injecting them wherever @Autowired is used.
  4. Launch the Application: Once everything is in place, the application goes live. Magic complete.

Real-Life Analogy: DI in a Coffee Shop

Think of your Spring Boot application as a coffee shop. You’re the owner, and the beans are your ingredients: coffee, milk, sugar, etc. Instead of running around managing these ingredients yourself, you’ve got a barista (the Spring container) who fetches everything and delivers it exactly where it’s needed.

All you have to do is give the orders (set up your @Autowired fields), and the barista handles the rest—perfectly brewing that dependency-filled cup of coffee for your customers (application).


Wrapping It Up: DI Is Your Superpower

At the end of the day, Dependency Injection is what makes Spring Boot such a powerful framework. It simplifies your life, manages your beans, and ensures your code is easy to maintain and extend.

Now that you’ve peeked behind the curtain, you’ve got a superpower that many developers take for granted. So go ahead—start using DI like the wizard you now are. And the next time you see @Autowired, you’ll know exactly what’s going on under the hood.


I hope this blog gave you a deeper understanding of Spring Boot DI and left you with a smile. Now go inject some beans and show your friends how it's done!


How’s that for a blog that’s fun, informative, and easy to understand? Let me know if you'd like any more tweaks!

以上是Spring Boot 中的依賴注入:幕後嚮導的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1663
14
CakePHP 教程
1420
52
Laravel 教程
1315
25
PHP教程
1266
29
C# 教程
1239
24
公司安全軟件導致應用無法運行?如何排查和解決? 公司安全軟件導致應用無法運行?如何排查和解決? Apr 19, 2025 pm 04:51 PM

公司安全軟件導致部分應用無法正常運行的排查與解決方法許多公司為了保障內部網絡安全,會部署安全軟件。 ...

如何將姓名轉換為數字以實現排序並保持群組中的一致性? 如何將姓名轉換為數字以實現排序並保持群組中的一致性? Apr 19, 2025 pm 11:30 PM

將姓名轉換為數字以實現排序的解決方案在許多應用場景中,用戶可能需要在群組中進行排序,尤其是在一個用...

如何使用MapStruct簡化系統對接中的字段映射問題? 如何使用MapStruct簡化系統對接中的字段映射問題? Apr 19, 2025 pm 06:21 PM

系統對接中的字段映射處理在進行系統對接時,常常會遇到一個棘手的問題:如何將A系統的接口字段有效地映�...

IntelliJ IDEA是如何在不輸出日誌的情況下識別Spring Boot項目的端口號的? IntelliJ IDEA是如何在不輸出日誌的情況下識別Spring Boot項目的端口號的? Apr 19, 2025 pm 11:45 PM

在使用IntelliJIDEAUltimate版本啟動Spring...

Java對像如何安全地轉換為數組? Java對像如何安全地轉換為數組? Apr 19, 2025 pm 11:33 PM

Java對象與數組的轉換:深入探討強制類型轉換的風險與正確方法很多Java初學者會遇到將一個對象轉換成數組的�...

如何優雅地獲取實體類變量名構建數據庫查詢條件? 如何優雅地獲取實體類變量名構建數據庫查詢條件? Apr 19, 2025 pm 11:42 PM

在使用MyBatis-Plus或其他ORM框架進行數據庫操作時,經常需要根據實體類的屬性名構造查詢條件。如果每次都手動...

電商平台SKU和SPU數據庫設計:如何兼顧用戶自定義屬性和無屬性商品? 電商平台SKU和SPU數據庫設計:如何兼顧用戶自定義屬性和無屬性商品? Apr 19, 2025 pm 11:27 PM

電商平台SKU和SPU表設計詳解本文將探討電商平台中SKU和SPU的數據庫設計問題,特別是如何處理用戶自定義銷售屬...

如何利用Redis緩存方案高效實現產品排行榜列表的需求? 如何利用Redis緩存方案高效實現產品排行榜列表的需求? Apr 19, 2025 pm 11:36 PM

Redis緩存方案如何實現產品排行榜列表的需求?在開發過程中,我們常常需要處理排行榜的需求,例如展示一個�...

See all articles