當前位置:編程學習大全網 - 源碼下載 - spring容器怎麽管理filter

spring容器怎麽管理filter

在使用spring容器的web應用中,業務對象間的依賴關系都可以用context.xml文件來配置,並且由spring容器來負責依賴對象 的創建。如果要在filter或者servlet中使用spring容器管理業務對象,通常需要使用

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中硬編碼要引用的對象名字。

  • 上一篇:有人知道《戀愛Live》裏圍城的歌詞嗎?
  • 下一篇:考慮考註冊會計師證之後做兼職,這個想法靠譜嗎
  • copyright 2024編程學習大全網