DelegatingFilterProxy源碼分析
DelegatingFilterProxy
org.springframework.web.filter.DelegatingFilterProxy
可以看出 DelegatingFilterProxy 類繼承 GenericFilterBean,間接實現(xiàn)了Filter這個接口,故而該類屬于一個過濾器。那么就會有實現(xiàn)Filter中 init、doFilter、destroy三個方法。
filter簡介:https://www.cnblogs.com/xdp-gacl/p/3948353.html
GenericFilterBean中實現(xiàn) filter中 init方法:
最后調(diào)用了
this.initFilterBean();
protected void initFilterBean() throws ServletException {
}
現(xiàn)在盯住 initFilterBean() 就ok了
public class DelegatingFilterProxy extends GenericFilterBean {
private String contextAttribute;
private WebApplicationContext webApplicationContext;
private String targetBeanName;
private boolean targetFilterLifecycle;
private volatile Filter delegate;
private final Object delegateMonitor;
...
protected void initFilterBean() throws ServletException {
Object var1 = this.delegateMonitor;
synchronized(this.delegateMonitor) {
if(this.delegate == null) {
if(this.targetBeanName == null) {
this.targetBeanName = this.getFilterName();
}
WebApplicationContext wac = this.findWebApplicationContext();
if(wac != null) {
this.delegate = this.initDelegate(wac);
}
}
}
}
...
}
在DelegatingFilterProxy 中繼承GenericFilterBean 重寫initFilterBean(),現(xiàn)在就可以解釋
如果不想用 filter-name: shiroFilter 也可以用 targerBeanName 的value 這句話了
- 在spring容器中去找與 filter-name 相同名字的 bean實例 如果沒有設(shè)置 targetBeanName 他會默認(rèn)去加載 filter-name 名字一樣的實例initFilterBean()
1、找到被代理類在spring中配置的id并賦值給targetBeanName。
2、使用找到的id從spring容器中找到具體被代理的類,并賦值給delegate
<!--Shiro過濾器-->
<filter>
<filter-name>shiroFilter</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>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>shiroFilter22</param-value>
</init-param>
</filter>
DelegatingFilterProxy
private String targetBeanName;
private boolean targetFilterLifecycle;
private volatile Filter delegate;
getFilterName()該方法的作用是,獲取被代理的filter在spring中配置的id
在這里插入圖片描述
private volatile Filter delegate; 獲取過濾器
initDelegate()該方法的作用是,從spring容器中獲取到具體被代理的filter
執(zhí)行doFilter()
invokeDelegate方法的作用就是執(zhí)行被代理filter的doFilter方法
在這里插入圖片描述private boolean targetFilterLifecycle; 默認(rèn)為false
判斷targetFilterLifecycle屬性是false還是true,決定是否調(diào)用自定義類的init()、destry()方法