javascript
如何:在Spring中使用@Conditional和Condition注册组件
Spring中的@Profile批注可以用于任何自動檢測候選的Spring組件(例如, @Service Component, @Service @Component , @Service @Configuration等)。 @Profile批注接受單個配置文件或一組必須是活動的配置文件,以使帶注釋的組件有資格進行自動檢測。 對于給定的@Profile({"p1", "!p2"}) ,如果配置文件p1處于活動狀態(tài)或配置文件p2不處于活動狀態(tài),則會進行注冊。 或至關(guān)重要。
但是如何使用@Profile來實現(xiàn)這一點:如果配置文件p1處于活動狀態(tài),并且配置文件p2 和 p3均處于非活動狀態(tài),我們想激活給定的組件嗎?
讓我們假設(shè)以下情況:我們有一個NotificationSender接口,該接口由以下方式實現(xiàn):
- SendGridNotificationSender –僅在sendgrid配置文件處于活動狀態(tài)時才處于活動狀態(tài),
- EmailNotificationSender –僅在email配置文件處于活動狀態(tài)時才處于活動狀態(tài)。
- NoOpNotificationSender –僅在development配置文件處于活動狀態(tài)且sendgrid和email沒有處于活動狀態(tài)時才處于活動狀態(tài)。
另外:一次只能注冊一個NotificationSender ,并且development配置文件可以與sendgrid和email配置文件結(jié)合使用。
在上述情況下,使用@Profile批注似乎還不夠。 也許我使事情變得有些復(fù)雜,但是實際上我真的很想實現(xiàn)上述目標而無需介紹其他配置文件。 我是怎么做到的?
我使用了Spring的4 @Conditional批注。 當所有指定Condition匹配時, @Conditional允許注冊組件:
@Component @Conditional(value = NoOpNotificationSender.ProfilesCondition.class) class NoOpNotificationSender extends NotificationSenderAdapter {}ProfilesCondition實現(xiàn)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);}} }當適當?shù)呐渲梦募幱诨顒訝顟B(tài)時,其他組件將被激活:
@Component @Profile(value = Profiles.SEND_GRID) public class SendGridNotificationSender extends NotificationSenderAdapter {}@Component @Profile(value = Profiles.MAIL) class EmailNotificationSender extends NotificationSenderAdapter {}用法示例:
| 發(fā)展 | NoOpNotificationSender |
| 開發(fā),sendgrid | SendGridNotificationSender |
| 開發(fā),郵件 | EmailNotificationSender |
| sendgrid | SendGridNotificationSender |
| 郵件 | EmailNotificationSender |
你怎么看? 您將如何解決這個問題?
翻譯自: https://www.javacodegeeks.com/2015/11/register-components-using-conditional-condition-spring.html
總結(jié)
以上是生活随笔為你收集整理的如何:在Spring中使用@Conditional和Condition注册组件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 惠州房子备案价查询惠民之家(惠州房子备案
- 下一篇: linux脚本if语句(linux if