简述
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