Springboot 自定义注解及接口多实现注入(策略模式)干掉ifelse

简述

Spring Boot 中提供完善的依赖注入机制,极其便利。本文分享接口多实现注入,与自定义注解的结合使用。

目标实现,根据自定义注解类型,选择接口实现。

本文实例属于典型的策略模式设计,减少复杂if else 方式,更加利于扩展。

项目依赖

Spring Boot:2.2.6.RELEASE

自定义注解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Service
public @interface Command {
    String type();
}
接口定义
public interface CustomHandler {
    /**
     * 处理
     * @param notice
     */
    void handle(Notice notice);
}
接口实现
@Command(type = "auto_allot")
@Service
@Slf4j
public class AutoAllotHandler implements CustomHandler {


    /**
     * 处理
     *
     * @param notice
     */
    @Override
    public void handle(Notice notice) {
       log.info("接收到消息:{}",notice)
    }
}

@LeadCommand(type = "add")
@Service
@Slf4j
public class LeadAddHandler implements CustomHandler {

    /**
     * 处理
     *
     * @param notice
     */
    @Override
    public void handle(Notice notice) {
        // 记录状态的时间
    }
}

服务注入及多实现调用

总结

完整版请阅读

https://xiaozhuanlan.com/topic/6083412795

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值