1,有时候算法需要迭代,相同的接口需要多个实现,自己可以随意切换,接口类:
package com.xxx.shortvideo.manager; public interface VideoRecommendedManger { FeedVideoByUserDTO getVideoByUser(FeedVideoByUserReq req); }2, 针对接口有两个实现
3,通过配置config类来实现
package com.xxxx.shortvideo.config; import com.xxxx.shortvideo.enums.BizTypeEnum; import com.xxxx.shortvideo.manager.VideoRecommendedManger; import com.xxxx.shortvideo.manager.impl.VideoRecHotWordMangerImpl; import com.xxxx.shortvideo.manager.impl.VideoRecommendedMangerImpl; import com.google.common.collect.Maps; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Map; @Configuration public class ShortVideoFillServiceConfig { @Autowired ApplicationContext applicationContext; @Bean Map<String, VideoRecommendedManger> shortVideoRecServiceMap() { Map<String, VideoRecommendedManger> shortVideoRecServiceMap = Maps.newHashMap(); shortVideoRecServiceMap.put(BizTypeEnum.SHORT_VIDEO_DEFAULT.getPrefix(), applicationContext.getBean(VideoRecommendedMangerImpl.class)); shortVideoRecServiceMap.put(BizTypeEnum.SHORT_VIDEO_HOT_WORD.getPrefix(), applicationContext.getBean(VideoRecHotWordMangerImpl.class)); return shortVideoRecServiceMap; } }
4,调用具体的实现
import javax.annotation.Resource; import java.util.Map; @RestController @RequestMapping("/facade/shortvideo") @Slf4j public class FeedVideoController { @Resource Map<String, VideoRecommendedManger> shortVideoRecServiceMap; //根据用户,获取video的list @RequestMapping(value = "/recommend", method = RequestMethod.POST) @PermissionCheck(skipAop=true) @ResponseBody public Res<FeedVideoByUserDTO> getVideoListByUserReq(@RequestBody FeedVideoByUserReq req) { try { FeedVideoByUserDTO videoByUser = null; if((BizTypeEnum.SHORT_VIDEO_HOT_WORD.getPrefix()).equals(req.getFlowTo())) { videoByUser = shortVideoRecServiceMap.get(BizTypeEnum.SHORT_VIDEO_HOT_WORD.getPrefix()).getVideoByUser(req); }else { videoByUser = shortVideoRecServiceMap.get(BizTypeEnum.SHORT_VIDEO_DEFAULT.getPrefix()).getVideoByUser(req); } log.info(String.format("用户推荐视频调用成功,返回:[%s]", JSON.toJSONString(videoByUser))); return Res.wrapSuccessfulResult(videoByUser); } catch (Exception e) { e.printStackTrace(); } return Res.wrapErrorResult(-1, "系统异常!"); } }5,注意事项:
5.1 如果 Map<String, HotelRecommendedManger> hotelRecServiceMap为String 类型:则需要 @Resource修饰
5.2如果 Map<Integer, HotelRecommendedManger> hotelRecServiceMap为Integer类型:则需要 @Autowire修饰