最近在水微信群时有人问了一个很好的问题,于是我知道,我装X的时刻又到了
问题描述:对于XXService的多种实现类不通过resource指定的情况下实现按功能动态注入
思路:使用拦截器对这个接口进行匹配拦截,通过接口参数来完成类型指定,通过反射完成注入
上代码
拦截器的
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object createController) throws Exception {
String type = httpServletRequest.getParameter("type");
ApplicationContext applicationContext =
WebApplicationContextUtils.getWebApplicationContext(httpServletRequest.getServletContext());
Field field = createController.getClass().getDeclaredField("createService");
field.setAccessible(true);
if("file".equals(type)) {
CreateServiceByFile createServiceByFile = applicationContext.getBean(CreateServiceByFile.class);