在使用springboo的時候,遇到一個問題,想在tool類中注入一個bean,一直失敗,翻了下源碼,是由於工具類的初始化方法爲反射class調用newInstance方法,詳見html
http://www.cnblogs.com/xiaoQLu/p/7292971.htmlspring
那還有沒有其餘方法實現呢,請教了組內的大神,丟了以下一段代碼我ide
@Configuration public class WebAppConfigTest extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new VelocityPageToolsInterceptor()); } } class VelocityPageToolsInterceptor extends AbstractPageRenderContextHandlerInterceptor { private static final Map<String, Object> ATTR_MAP = Maps.newHashMap(); static { Class<?> dateTool = ClassUtils.resolveClassName("com.xx.xx.類名", WebAppConfig.class.getClassLoader()); ATTR_MAP.put("dateTool", BeanUtils.instantiate(dateTool)); } @Override protected void postHandleOnPageRenderContext(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext()); modelAndView.getModel().put("testUtil", context.getBean("testUtil")); modelAndView.getModel().putAll(ATTR_MAP); } }
上面最關鍵的代碼就是 ModelAndView.getModel().put("", "")方法,就是把對象放到model中工具