适用的场景
例如一个汇报分为文件签批、工作汇报、工作指引等类型
正常可能会有一个抽象的类,下面三个或多个实现类的形式
如果想要根据数据的某一个字段去实现区分,例如文件签批类型的走文件签批的实现类代码,工作汇报类型的走工作汇报类型的实现类代码这种,
按照以往正常的使用@Autowired的方式注入,@Autowired
private UserFeign userFeign 匹配UserFeign 再去匹配userFeign 的方式不适用,因为我们走的是数据库的某个字段去进行区分,并且这个字段已经被我们实例化的存储在数据库中
这个时候可以使用工厂实例的方式去进行解决:
以下是实现的用例:
下面展示一些 内联代码片
。
工厂实例
@Slf4j
@Service
public class ReportRecordFactory implements ApplicationContextAware {
private static final Map<Integer, IReportRecordService> beanMap = new HashMap<>();
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
Map<String, IReportRecordService> beansList = applicationContext.getBeansOfType(IReportRecordService.class);
if (CollectionUtils.isEmpty(beansList)) {
log.error("[ReportRecordFactory] setApplicationContext. beansList of IReportRecordService not found");
return;
}
for (IReportRecordService bean : beansList.values()) {
Integer type = bean.getType();
if (Objects.isNull(type)) {
continue;
}
beanMap.put(type, bean);
log.info("[ReportRecordFactory] setApplicationContext. type={}, beanName={}", type, bean.getClass().getName());
}
}
public static IReportRecordService getBean(Integer type) {
if (!beanMap.containsKey(type)) {
throw new BusinessException("[ReportRecordFactory] failed to get IReportRecordService bean");
}
return beanMap.get(type);
}
}
public interface IReportRecordService {
/**
* 汇报类型
*
* @see ReportConstant.ReportRecordTypeEnum
*/
Integer getType();
}
枚举
/**
* 汇报
*/
public class ReportConstant {
/**
* 工作汇报类型: 1-工作交流、2-工作指引、3-文件签批、4-AI汇报、5-工作汇报
*/
@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum ReportRecordTypeEnum {
工作交流(1, "communication", "交流"),
工作指引(2, "lead", "指引"),
文件签批(3, "sign", "签批"),
AI汇报(4, "feedback", "建议"),
工作汇报(5, "report", "汇报");
private Integer type;
private String name;
private String shortName;
public static List<Integer> allTypes() {
return Arrays.stream(values()).map(ReportRecordTypeEnum::getType).collect(Collectors.toList());
}
public static String getShortName(Integer type) {
for (ReportRecordTypeEnum reportRecordTypeEnum : ReportRecordTypeEnum.values()) {
if (reportRecordTypeEnum.getType().equals(type)) {
return reportRecordTypeEnum.getShortName();
}
}
return null;
}
}
}
调用
public ReportRecordVO detail(Long reportRecordId, Long empId, Boolean isRefreshLookTime) {
ReportRecord reportRecord = selectReportRecordById(reportRecordId);
return ReportRecordFactory.getBean(reportRecord.getReportRecordType()).detail(reportRecord, empId, isRefreshLookTime);
}