前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JAVA service多实现基操

JAVA service多实现基操

原创
作者头像
时光_赌徒
修改2021-04-25 11:04:14
5480
修改2021-04-25 11:04:14
举报
文章被收录于专栏:记录记录

先上需要用到得类:

1、自定义注解

代码语言:javascript
复制
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface BeanType {
    public String[] value() default {};
}
代码语言:javascript
复制

Component
public class SpringBeanUtilExt implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static <T> T getBeanByType(String type, Class<T> enumCla) throws Exception {
        Map<String, T> beansMap = applicationContext.getBeansOfType(enumCla);
        for (T t : beansMap.values()) {
            String[] invokes;
            BeanType annotation = AopUtils.getTargetClass(t).getAnnotation(BeanType.class);
            invokes = (String[]) annotation.annotationType().getMethod("value").invoke(annotation);
            for (String str : invokes) {
                if (StringUtil.equals(type, str)) {
                    return t;
                }
            }
        }
        throw new GroupSignInException(ResultCode.VALIDATION_EXCEPTION, "错误的业务类型");
    }


    public static <T> Object getPaeamObject(T instance, int index, Map<String, Object> map, Class interfaceCls) {
        if (instance == null || map == null) {
            throw new GroupSignInException(ResultCode.VALIDATION_EXCEPTION, "传输参数错误");
        }
        return MapUtil.mapToBean(map, getGenericsClass(instance, index, interfaceCls));
    }

    private static Class getGenericsClass(Object obj, int index, Class interfaceCls) {
        ResolvableType[] resolvableTypeArray = ResolvableType.forClass(AopUtils.getTargetClass(obj)).getInterfaces();
        if (resolvableTypeArray == null || resolvableTypeArray.length <= 0) {
            resolvableTypeArray = ResolvableType.forClass(AopUtils.getTargetClass(obj)).getSuperType().getInterfaces();
            if (resolvableTypeArray == null || resolvableTypeArray.length <= 0) {
                throw new GroupSignInException(ResultCode.VALIDATION_EXCEPTION, "未实现接口");
            }
        }
        for (ResolvableType resolvableType : resolvableTypeArray) {
            if (resolvableType.resolve().getName().equals(interfaceCls.getName())) {
                return resolvableType.getGeneric(index).resolve();
            }
        }
        throw new GroupSignInException(ResultCode.VALIDATION_EXCEPTION, "未实现指定接口");
    }
}

实体和Map转化

代码语言:javascript
复制
public class MapUtil {

    public static final Logger logger = LoggerFactory.getLogger(MapUtil.class);

    /**
     * map转javaBean
     *
     * @param source
     * @param instance
     * @param <T>
     * @return
     */
    public static <T> T mapToBean(Map<String, Object> source, Class<T> instance) {
        try {
            T obejct = instance.newInstance();
            Field[] fields = obejct.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                if (source.get(field.getName()) == null) {
                    continue;
                }
                if (field.getType().equals(Map.class)) {
                    field.set(obejct, source.get(field.getName()));
                    continue;
                }

                // 处理对象中包含另一对象的实现
                if (source.get(field.getName()) != null && source.get(field.getName()).getClass().equals(LinkedHashMap.class)) {
                    Map<String, Object> map = (LinkedHashMap<String, Object>) source.get(field.getName());
                    if (map.keySet().size() > 1) {
                        field.set(obejct, mapToBean(map, field.getType()));
                        continue;
                    }
                }
                if (source.get(field.getName()) != null && source.get(field.getName()).getClass().equals(ArrayList.class) && field.getType().getComponentType() != null) {
                    List<LinkedHashMap> listObj = (ArrayList<LinkedHashMap>) source.get(field.getName());
                    if (CollectionUtils.isNotEmpty(listObj)) {
                        List objList = new ArrayList();
                        for (LinkedHashMap map : listObj) {
                            if (map.keySet().size() > 1) {
                                if (field.getType().equals(ArrayList.class)) {
                                    field.set(obejct, source.get(field.getName()));
                                } else {
                                    objList.add(mapToBean(map, field.getType().getComponentType()));
                                }
                            }
                        }
                        field.set(obejct, objArrToTarr(objList.toArray(), field.getType().getComponentType()));
                    }
                    continue;
                }
                // 时间类型处理 只能传入 时间戳
                if (field.getType().equals(Date.class)) {
                    field.set(obejct, new Date((Long) (source.get(field.getName()))));
                } else {
                    field.set(obejct, source.get(field.getName()));
                }
            }
            return obejct;
        } catch (InstantiationException e) {
            logger.error("", e);
        } catch (IllegalAccessException e) {
            logger.error("", e);
        }
        return null;
    }

    /**
     * Obj[] to T[]
     *
     * @param objArr
     * @param instance
     * @param <T>
     * @return
     */
    private static <T> T[] objArrToTarr(Object[] objArr, Class<T> instance) {
        Object obj = Array.newInstance(instance, objArr.length);
        System.arraycopy(objArr, 0, obj, 0, objArr.length);
        T[] res = (T[]) obj;
        return res;
    }

    /**
     * javaBean转map
     *
     * @param source
     * @param source
     * @param <T>
     * @return
     */
    public static <T> Map<String, Object> beanToMap(T source) {
        Map<String, Object> result = new HashMap<>();
        try {
            Class<?> soultClass = source.getClass();
            Field[] fields = soultClass.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                result.put(field.getName(), field.get(source));
            }
        } catch (IllegalAccessException e) {
            logger.error("", e);
        }
        return result;
    }
}

根据业务需要service多实现类:

每个实现类用@BeanType({"你定义的code"})

获取相关实现类 直接传递想用得BeanType

AfterProcessStatusService【接口名称】 afterProcessStatusService = SpringBeanUtilExt.getBeanByType(applyInfoDto.getCallBackCode()【beantype值】, AfterProcessStatusService.class);

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档