当前位置: 代码迷 >> Web前端 >> Web Filter中运用Spring注入bean
  详细解决方案

Web Filter中运用Spring注入bean

热度:1128   发布时间:2012-09-01 09:33:02.0
Web Filter中使用Spring注入bean
方法一:
web.xml配置一个
    <filter>
        <filter-name>DelegatingFilterProxy</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetBeanName</param-name>
            <param-value>myFilter</param-value>         //自己过滤器的名字
        </init-param>
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>DelegatingFilterProxy</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

方法二:
web.xml配置一个
    <filter>
        <filter-name>myFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>DelegatingFilterProxy</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


方法一或者二不同的地方就是在web.xml中的写法不同而已没有太大的区别,配完web.xml之后还要配置applicationContext.xml中的bean。

applicationContext.xml配置:
<bean id="myFilter" class="com.filter.MyFilter"> //指名具体的filter类
    <property name="service">                    //需要注入的具体参数
        <ref bean="service"/>
    </property>
</bean>
<bean id="service" parent="baseTransactionProxy">//这里的service封装了所有对数据库的操作
        <property name="target">
            <bean class="com.maimaiche.service.MaiMaiCheServiceImpl">
             ......
             </bean>
       </property>
</bean>
  相关解决方案