详解Spring Controller autowired Request变量
详解SpringControllerautowiredRequest变量
spring的DI大家比较熟悉了,对于依赖注入的实现也无须赘述。
那么spring的bean的默认scope为singleton,对于controller来说每次方法中均可以获得request还是比较有意思的。
对于方法参数上的request通过构建方法的参数可以获得最新的request
publicfinalObjectinvokeForRequest(NativeWebRequestrequest,ModelAndViewContainermavContainer, Object...providedArgs)throwsException{ Object[]args=getMethodArgumentValues(request,mavContainer,providedArgs); if(logger.isTraceEnabled()){ StringBuildersb=newStringBuilder("Invoking["); sb.append(getBeanType().getSimpleName()).append("."); sb.append(getMethod().getName()).append("]methodwitharguments"); sb.append(Arrays.asList(args)); logger.trace(sb.toString()); } ObjectreturnValue=invoke(args); if(logger.isTraceEnabled()){ logger.trace("Method["+getMethod().getName()+"]returned["+returnValue+"]"); } returnreturnValue; }
2.对于controller等单实例变量来说如何动态注入变量呢?spring使用了很聪明的办法
- 首先request和用户请求相关
- 不同的用户同时访问时是在不同的线程中
- 保存了用户的请求在threadlocal中
- 用户获取该请求需要手动调用threadlocal来获取
- 为了帮助用户减少重复代码,spring可以让用户‘动态'注入request
- 当controller在实例化时,动态注册一个proxy到当前request变量中
- 此proxy当被使用是可以将所有方法动态路由到threadlocal中该request变量上执行
/** *Registerweb-specificscopes("request","session","globalSession","application") *withthegivenBeanFactory,asusedbytheWebApplicationContext. *@parambeanFactorytheBeanFactorytoconfigure *@paramsctheServletContextthatwe'rerunningwithin */ publicstaticvoidregisterWebApplicationScopes(ConfigurableListableBeanFactorybeanFactory,ServletContextsc){ beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST,newRequestScope()); beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION,newSessionScope(false)); beanFactory.registerScope(WebApplicationContext.SCOPE_GLOBAL_SESSION,newSessionScope(true)); if(sc!=null){ ServletContextScopeappScope=newServletContextScope(sc); beanFactory.registerScope(WebApplicationContext.SCOPE_APPLICATION,appScope); //RegisterasServletContextattribute,forContextCleanupListenertodetectit. sc.setAttribute(ServletContextScope.class.getName(),appScope); } beanFactory.registerResolvableDependency(ServletRequest.class,newRequestObjectFactory()); beanFactory.registerResolvableDependency(HttpSession.class,newSessionObjectFactory()); beanFactory.registerResolvableDependency(WebRequest.class,newWebRequestObjectFactory()); if(jsfPresent){ FacesDependencyRegistrar.registerFacesDependencies(beanFactory); } }
/** *Factorythatexposesthecurrentrequestobjectondemand. */ @SuppressWarnings("serial") privatestaticclassRequestObjectFactoryimplementsObjectFactory,Serializable{ publicServletRequestgetObject(){ returncurrentRequestAttributes().getRequest(); } @Override publicStringtoString(){ return"CurrentHttpServletRequest"; } }
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!