SPRING与设计模式--单件模式

本文探讨了Spring Security中单例模式的应用,并介绍了AndRequestMatcher类的实现细节,该类通过组合多个RequestMatcher来判断HTTP请求是否匹配指定的规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SPRING与设计模式--单件模式

单体模式是一种常用的模式,顾名思义就是一个类只允许有一个实例。springsecurity大都使用饿汉模式,在类加载时就创建好了实例。其他模式见:https://www.jianshu.com/p/c7ca51d2816e


 AnyRequestMatcher源码:

package org.springframework.security.web.util.matcher;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;

/**
 * {@link RequestMatcher} that will return true if all of the passed in
 * {@link RequestMatcher} instances match.
 *
 * @author Rob Winch
 * @since 3.2
 */
public final class AndRequestMatcher implements RequestMatcher {
	private final Log logger = LogFactory.getLog(getClass());

	private final List<RequestMatcher> requestMatchers;

	/**
	 * Creates a new instance
	 *
	 * @param requestMatchers the {@link RequestMatcher} instances to try
	 */
	public AndRequestMatcher(List<RequestMatcher> requestMatchers) {
		Assert.notEmpty(requestMatchers, "requestMatchers must contain a value");
		if (requestMatchers.contains(null)) {
			throw new IllegalArgumentException(
					"requestMatchers cannot contain null values");
		}
		this.requestMatchers = requestMatchers;
	}

	/**
	 * Creates a new instance
	 *
	 * @param requestMatchers the {@link RequestMatcher} instances to try
	 */
	public AndRequestMatcher(RequestMatcher... requestMatchers) {
		this(Arrays.asList(requestMatchers));
	}

	public boolean matches(HttpServletRequest request) {
		for (RequestMatcher matcher : requestMatchers) {
			if (logger.isDebugEnabled()) {
				logger.debug("Trying to match using " + matcher);
			}
			if (!matcher.matches(request)) {
				logger.debug("Did not match");
				return false;
			}
		}
		logger.debug("All requestMatchers returned true");
		return true;
	}

	@Override
	public String toString() {
		return "AndRequestMatcher [requestMatchers=" + requestMatchers + "]";
	}
}
工厂模式用于对象生成,是整个spring框架的核心模式,借助配置信息获取要生成的对象的信息,开发者要使用的对象都从spring容器中获取。在工厂模式会做更具体的描述讲解
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值