WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext())來獲得WebApplicationContext,然後調用WebApplicationContext.getBean("beanName")來獲得對象的引用,這實際上是使用了依賴查找來獲得對象,並且在filter或者servlet代碼中硬編碼了應用對象的bean名字。為了能在filter或者servlet中感知spring中bean,可采用如下步驟來實現:
1- 將filter或者servlet作為bean定義在context.xml文件中,和要應用的bean定義放在壹起;
2- 實現壹個filter代理或者servlet代理,該代理用WebApplicationContext來獲得在context.xml中定義的filter或者servlet的對象,並將任務委托給context.xml中定義的filter或者servlet
3- 在web.xml中用ContextLoaderListener來初始化spring 的context,同時在filter代理或者servlet代理的定義中用初始化參數來定義context.xml中filter或者servlet的bean名字(或者直接受用代理的名稱獲得相應的filter或者servlet的名稱)。
4- 在web.xml中定義filter代理或者servlet代理的mapping.
利用這種方式就將filter或者servlet和業務對象的依賴關系用spring 來進行管理,並且不用在servlet中硬編碼要引用的對象名字。