spring-security中DelegatingFilterProxy的delegateMonitor的作用

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()这样的的并发环境中需要双重检查锁来进行赋值。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值