JAVA 工具类Factory
/** * @author yong.liu
* @date 2020/7/30
*/
public abstract class AbstractHandlerFactory<T,K extends HandlerSelector <T>> implements HandlerFactory <T,K>, BeanFactoryAware , InitializingBean {
private Map<T, K> serviceMap;
private ConfigurableListableBeanFactory beanFactory;
@Override
public K getService(T t) {
return serviceMap.get(t);
}
@Override
public void afterPropertiesSet() throws Exception {
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
Type[] types = pt.getActualTypeArguments();
Class<K> interfaceClazz = (Class<K>)types[1];
// logger.info("可选服务初始化,服务接口为{},默认实现为{}", interfaceClazz.getName(), interfaceClazz.getName());
Map<String, K> serviceBeanMap = beanFactory.getBeansOfType(interfaceClazz);
serviceMap = new HashMap<T , K>(serviceBeanMap.size());
for (K processor : serviceBeanMap.values()) {
if (!(processor instanceof HandlerSelector)) {
throw new RuntimeException("实现类必须实现ProcessorSelector接口!");
}
// 如果已经存在相同受理机构的服务,则抛出错误
HandlerSelector<T> selector = (HandlerSelector)processor;
if (null != serviceMap.get(selector.getType())) {
throw new RuntimeException("已经存在Type【" + selector.getType() + "】的服务");
}
serviceMap.put(selector.getType(), processor);
}
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
if (beanFactory instanceof DefaultListableBeanFactory) {
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
}
}
}
public interface HandlerSelector<T> { /**
* 获取选择器类型
*
* @return
*/
T getType();
}
public interface HandlerFactory<T, K extends HandlerSelector<T>> { /**
* 获取对应的服务
*
* @param t
* @return
*/
K getService(T t);
}
使用:
public inteface SubsidyStatHandler implements HandlerSelector<String>{ public void dosth()
}
@Service
public class SubsidyStatHandlerFactroy extends AbstractHandlerFactory<Integer, SubsidyStatHandler> {
}
以上是 JAVA 工具类Factory 的全部内容, 来源链接: utcz.com/z/394148.html