济南网站制作经验wordpress建外贸网站
web/
2025/10/8 23:07:45/
文章来源:
济南网站制作经验,wordpress建外贸网站,即墨区建设局网站,杭州网站建设费用Spring中的Profile批注可以用于任何自动检测候选的Spring组件#xff08;例如#xff0c; Service Component#xff0c; Service Component #xff0c; Service Configuration等#xff09;。 Profile批注接受单个配置文件或一组必须是活动的配置文件#xff0c;以使带… 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
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/89316.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!