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);
}

浙公网安备 33010602011771号