spring-security中DelegatingFilterProxy的delegateMonitor的作用
首先让我看标记处delegateMonitor在DelegatingFilterProxy类中出现的位置
- 在属性域的声明和赋值
private final Object delegateMonitor = new Object();
- 在bean初始化后执行的代码中
protected void initFilterBean() throws ServletException {
synchronized (this.delegateMonitor) {
if (this.delegate == null) {
if (this.targetBeanName == null) {
this.targetBeanName = getFilterName();
}
WebApplicationContext wac = findWebApplicationContext();
if (wac != null) {
this.delegate = initDelegate(wac);
}
}
}
}
- 在请求处理方法doFilter中
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
Filter delegateToUse = this.delegate;
if (delegateToUse == null) {
synchronized (this.delegateMonitor) {
if (this.delegate == null) {
WebApplicationContext wac = findWebApplicationContext();
if (wac == null) {
throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?");
}
this.delegate = initDelegate(wac);
}
delegateToUse = this.delegate;
}
}
invokeDelegate(delegateToUse, request, response, filterChain);
}
我们可以看到delegateMonitor的字面意思的委托监控,它是如何监控的呢?
首先它被赋予了一个Object对象,然后他的使用都在synchronized关键字中,作用很明显,就是防止出现并发的情况,对delegate属性赋予多次值。
为什么会出现这样的情况呢?在initFilterBean()方法中使用synchronized中不太清楚有什么作用,因为filter的init方法只会在实例化后立马执行,且只会执行一次,并不存在什么并发的情况。而在doFilter()中使用synchronized就容易理解了,因为可能在同一时刻会发生多次http请求。有的同学会感到很奇怪,为什么的initFilterBean()中已经对delegate进行赋值了,那么为什么要在doFilter()中进行判断。这里展示一下原因:
// Fetch Spring root application context and initialize the delegate early,
// if possible. If the root application context will be started after this
// filter proxy, we'll have to resort to lazy initialization.
WebApplicationContext wac = findWebApplicationContext();
其大意是在对Spring应用程序上下文初始化的时候,可能会发生初始化还没有完成的情况就已经实例化这个filter了,所以我们需要的doFilter()中再次判断delegate的值是不是null。如果是null,在doFilter()这样的的并发环境中需要双重检查锁来进行赋值。