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
spring到底是干啥的public void handle(Notice notice){
// 记录状态的时间
}
}
服务注⼊及多实现调⽤
总结
完整版请阅读

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。