日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

conditional_如何:在Spring中使用@Conditional和Condition注册组件

發布時間:2023/12/3 javascript 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 conditional_如何:在Spring中使用@Conditional和Condition注册组件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

conditional

Spring中的@Profile批注可用于任何自動檢測候選對象的Spring組件(例如, @Service Component, @Service @Component , @Service @Configuration等)。 @Profile批注接受單個配置文件或一組必須是活動的配置文件,以使帶注釋的組件有資格進行自動檢測。 對于給定的@Profile({"p1", "!p2"}) ,如果配置文件p1處于活動狀態配置文件p2不處于活動狀態,則會進行注冊。 至關重要。

但是,如何使用@Profile實現此目標:如果配置文件p1處于活動狀態并且配置文件p2 p3均處于非活動狀態,我們想激活給定的組件嗎?

讓我們假設以下情況:我們有一個NotificationSender接口,該接口由以下方式實現:

  • SendGridNotificationSender –僅在sendgrid配置文件處于活動狀態時才處于活動狀態,
  • EmailNotificationSender –僅在email配置文件處于活動狀態時才活動。
  • NoOpNotificationSender –僅在development配置文件處于活動狀態且sendgrid和email沒有處于活動狀態時才處于活動狀態。

另外:一次只能注冊一個NotificationSender , development配置文件可以與sendgrid和email配置文件結合使用。

在上述情況下,使用@Profile注釋似乎還不夠。 也許我使事情變得有些復雜,但實際上我真的很想實現上述目標而沒有介紹其他配置文件。 我是怎么做到的?

我使用了Spring的4 @Conditional注釋。 當所有指定Condition匹配時, @Conditional允許注冊組件:

@Component @Conditional(value = NoOpNotificationSender.ProfilesCondition.class) class NoOpNotificationSender extends NotificationSenderAdapter {}

ProfilesCondition實現org.springframework.context.annotation.Condition接口:

public static class ProfilesCondition implements Condition {@Overridepublic boolean matches(ConditionContext c, AnnotatedTypeMetadata m) {} }

問題的整體解決方案:

@Component @Conditional(value = NoOpNotificationSender.ProfilesCondition.class) class NoOpNotificationSender extends NotificationSenderAdapter {static class ProfilesCondition implements Condition {@Overridepublic boolean matches(ConditionContext c, AnnotatedTypeMetadata m) {return accepts(c, Profiles.DEVELOPMENT)&& !accepts(c, Profiles.MAIL)&& !accepts(c, Profiles.SEND_GRID);}private boolean accepts(ConditionContext c, String profile) {return c.getEnvironment().acceptsProfiles(profile);}} }

當適當的配置文件處于活動狀態時,其他組件將被激活:

@Component @Profile(value = Profiles.SEND_GRID) public class SendGridNotificationSender extends NotificationSenderAdapter {}@Component @Profile(value = Profiles.MAIL) class EmailNotificationSender extends NotificationSenderAdapter {}

用法示例:

活動資??料 豆
發展 NoOpNotificationSender
開發,sendgrid SendGridNotificationSender
開發,郵件 EmailNotificationSender
sendgrid SendGridNotificationSender
郵件 EmailNotificationSender


你怎么看? 您將如何解決這個問題?

翻譯自: https://www.javacodegeeks.com/2015/11/register-components-using-conditional-condition-spring.html

conditional

總結

以上是生活随笔為你收集整理的conditional_如何:在Spring中使用@Conditional和Condition注册组件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。