假如有一个查询接口,入参和出参形式一致,则可以进行封装,可以通过 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;}}