知識庫 / Spring / Spring Boot RSS 訂閱

Spring @ConditionalOnProperty 註解

Spring Boot
HongKong
5
12:46 PM · Dec 06 ,2025

1. 概述

本教程將探討主 目的,即 @ConditionalOnProperty 註解的作用。

首先,我們將介紹一下 @ConditionalOnProperty 的基本概念。然後,我們將分析一些實際示例,以幫助您理解其工作原理以及它所帶來的功能。

2. @ConditionalOnProperty 的目的

通常,在開發基於 Spring 的應用程序時,我們需要根據配置屬性的存在和值來創建一些 Bean

例如,我們可能想要註冊一個 DataSource Bean,以便根據我們設置的屬性值(例如“prod”或“test”)來指向生產數據庫或測試數據庫。

幸運的是,實現這一點比初 glance 看上去要容易得多。 Spring 框架提供了 @ConditionalOnProperty 註解,正是為了解決這個問題。

簡而言之,@ConditionalOnProperty 允許 Bean 註冊僅當環境屬性存在且具有特定值時才啓用。 默認情況下,指定屬性必須被定義並且不等於 false

現在,我們對 @ConditionalOnProperty 註解的目的有了初步的瞭解,接下來讓我們深入瞭解它的工作原理。

3. @ConditionalOnProperty 註解在實踐中的應用

為了説明 `@ConditionalOnProperty` 註解的使用,我們將開發一個基本的通知系統。為了簡化當前實現,我們假設我們想要發送電子郵件通知。

首先,我們需要創建一個簡單的服務來發送通知消息。例如,考慮一下 NotificationSender 接口:

public interface NotificationSender {
    String send(String message);
}

接下來,我們提供 NotificationSender 接口的實現,用於發送我們的電子郵件:

public class EmailNotification implements NotificationSender {
    @Override
    public String send(String message) {
        return "Email Notification: " + message;
    }
}

現在讓我們看看如何利用 @ConditionalOnProperty 註解。 讓我們以一種方式配置 NotificationSender Bean,使其僅在 notification.service 屬性已定義時才加載

@Bean(name = "emailNotification")
@ConditionalOnProperty(prefix = "notification", name = "service")
public NotificationSender notificationSender() {
    return new EmailNotification();
}

如我們所見,`prefix 和 name 屬性用於表示應進行檢查的配置屬性。

最後,我們需要添加拼圖的最後一塊。讓我們在 application.properties 文件中定義我們的自定義屬性:

notification.service=email

4. 高級配置

正如我們已經學到的,<em @ConditionalOnProperty</em>> 註解允許我們根據配置屬性的存在情況,條件地註冊 Bean。

但是,我們不僅可以使用這個註解來做這些事情。讓我們一起探索一下!

假設我們想要添加另一個通知服務,例如一個能夠發送短信通知的服務。

要做到這一點,我們需要創建一個新的 <em NotificationSender</em> 實現:

public class SmsNotification implements NotificationSender {
    @Override
    public String send(String message) {
        return "SMS Notification: " + message;
    }
}

由於我們有兩套實現,讓我們看看如何使用 @ConditionalOnProperty 來加載合適的 NotificationSender Bean。

為此,該註解提供了 havingValue 屬性。 值得注意的是, 定義了屬性必須具有的值,以便將特定 Bean 添加到 Spring 容器中

現在,讓我們指定在什麼條件下在上下文中註冊 SmsNotification 實現。

@Bean(name = "smsNotification")
@ConditionalOnProperty(prefix = "notification", name = "service", havingValue = "sms")
public NotificationSender notificationSender2() {
    return new SmsNotification();
}

藉助<em>havingValue</em>屬性,我們明確表示只有當<em>SmsNotification</em>才應加載,且<em>notification.service</em>設置為<em>sms</em>。

值得一提的是,<em>@ConditionalOnProperty</em> 還有一個名為 <a href="https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/condition/ConditionalOnProperty.html#matchIfMissing--">

現在,讓我們將所有組件組合起來,並編寫一個簡單的測試用例以確認一切按預期工作:

@Test
public void whenValueSetToEmail_thenCreateEmailNotification() {
    this.contextRunner.withPropertyValues("notification.service=email")
        .withUserConfiguration(NotificationConfig.class)
        .run(context -> {
            assertThat(context).hasBean("emailNotification");
            NotificationSender notificationSender = context.getBean(EmailNotification.class);
            assertThat(notificationSender.send("Hello From Baeldung!")).isEqualTo("Email Notification: Hello From Baeldung!");
            assertThat(context).doesNotHaveBean("smsNotification");
        });
}

5. 結論

在本文中,我們重點介紹了使用 <em @ConditionalOnProperty</em> 註解的目的。 此外,我們還學習瞭如何使用它通過一個實際示例來條件加載 Spring Bean。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.