SpringBoot工厂----继承ApplicationContextAware
SpringBoot工厂模式----继承ApplicationContextAware
MallService
public interface MallService {
/**
* 商城类型
*
* @return 商城类型代码
*/
String mallType();
}
register
@Slf4j
@Component
public class MallServiceRepository {
private static final Map<Integer, MallService> SERVICE_MAP = new ConcurrentHashMap<>();
@SuppressWarnings("unchecked")
public <T extends MallService> T getMallService(Class<T> clazz, @NonNull String mallType) {
return (T) SERVICE_MAP.get(generateServiceKey(clazz.getTypeName(), mallType));
}
/**
* 注册服务
*
* @param service 平台服务
*/
public void register(MallService service) {
Type[] types = service.getClass().getGenericInterfaces();
if (!Assert.isEmpty(types)) {
for (Type type : types) {
register(type.getTypeName(), service);
}
} else {
register(service.getClass().getTypeName(), service);
}
}
private void register(String className, MallService service) {
SERVICE_MAP.put(generateServiceKey(className, service.mallType()), service);
log.info("注册平台服务:{},{}", className, service.mallType());
}
private int generateServiceKey(String className, @NonNull String mallType) {
return Objects.hash(className, mallType.toLowerCase());
}
}
factory
@Component
public class MallServiceBootstrap implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Resource
private MallServiceRepository repository;
@Override
public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@PostConstruct
public void init() {
Map<String, ? extends MallService> beanMap = applicationContext.getBeansOfType(MallService.class);
for (MallService service : beanMap.values()) {
repository.register(service);
}
}
}
service的实现类
public interface MallAuthService extends MallService{
/**
* 获取授权地址
*
* @return 授权地址URL
*/
String getAuthUrl();
/**
* 授权
*/
void createToken();
/**
* 刷新授权
*/
void refreshToken();
}
单元测试
@Resource
private MallServiceRepository mallServiceRepository;
@Test
public void getTaobaoOrderServiceTest() {
MallOrderService orderService = mallServiceRepository.getMallService(MallOrderService.class, "taobao");
assertNotNull(orderService);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下