您的位置:首页 > 游戏 > 游戏 > Spring Boot 干掉 if else 系列之反射大法

Spring Boot 干掉 if else 系列之反射大法

2024/10/6 12:35:21 来源:https://blog.csdn.net/z1353095373/article/details/135645076  浏览:    关键词:Spring Boot 干掉 if else 系列之反射大法

假如有一个查询接口,入参和出参形式一致,则可以进行封装,可以通过 type 进行区分,常规方法直接 if else,但如果太多了,代码很难受,策略模式吧,类又太多了,也很难受。那么,何不使用反射?只需如此这般…

    @PostMapping("/list/{type}")public R<Object> queryList(@PathVariable String type, @RequestBody ScreenDTO request) {return R.ok(screenQueryService.queryList(type, request));}
import cn.hutool.core.bean.DynaBean;
import cn.hutool.extra.spring.SpringUtil;
import com.la.security.yunaq.domain.ScreenDTO;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** 大屏相关数据查询** @author jason* @since 2023-08-09*/
@Component
@Import(cn.hutool.extra.spring.SpringUtil.class)
public class ScreenQueryService implements InitializingBean {private final Map<String, String[]> beanInfomap = new HashMap<>();@Overridepublic void afterPropertiesSet() {// 被攻击资产排名 top10beanInfomap.put("attack_top", new String[]{"yunaqAttackCollectServiceImpl", "getAttackTopList"});// 应⽤安全beanInfomap.put("app_safe", new String[]{"yunaqAttackCollectServiceImpl", "getAppSafeList"});}/*** 列表查询*/public List<?> queryList(String type, ScreenDTO request) {String[] beanInfo = beanInfomap.get(type);Object obj = SpringUtil.getBean(beanInfo[0]);DynaBean bean = DynaBean.create(obj);Object invoke = bean.invoke(beanInfo[1], request);return (List<?>) invoke;}}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com