Spring Security Config : 安全构建器抽象基类 AbstractSecurityBuilder

博客介绍了概念模型接口安全构建器的抽象实现,它作为基类供具体实现类使用。约定目标对象最多构建一次,通过标志位控制,构建器方法返回泛型目标对象。该基类不执行具体构建,将构建方法设定特定值,由具体类提供构建逻辑,源代码版本为Spring Security Config 5.1.4.RELEASE。

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

AbstractSecurityBuilderSpring Security Config对概念模型接口安全构建器SecurityBuilder的抽象实现,该类被用作各个安全构建器具体实现类的基类。

该抽象基类约定了使用此类构建器对象构建目标对象时,目标对象被构建最多一次。该行为是通过使用一个AtomicBoolean building标志位来控制的。只有在该标志为false时,调用构建器的#build方法才会触发执行目标对象的构建逻辑。如果该标志为true时调用构建器的#build方法,则会出现异常AlreadyBuiltException("This object has already been built")

构建器方法#build的返回值为目标构建对象,类型为泛型O

该抽象基类并不真正执行具体的目标对象构建,它将SecurityBuilder约定的构建方法#build设定为final,但是又定义了一个抽象方法#doBuild让具体实现类提供真正的目标对象构建逻辑。

源代码

源代码版本 : Spring Security Config 5.1.4.RELEASE

package org.springframework.security.config.annotation;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * A base SecurityBuilder that ensures the object being built is only built one
 * time.
 *
 * @param <O> the type of Object that is being built
 *
 * @author Rob Winch
 *
 */
public abstract class AbstractSecurityBuilder<O> implements SecurityBuilder<O> {
	private AtomicBoolean building = new AtomicBoolean();

	private O object;

	/*
	 *
	 * @see org.springframework.security.config.annotation.SecurityBuilder#build()
	 */
	public final O build() throws Exception {
		if (this.building.compareAndSet(false, true)) {
			this.object = doBuild();
			return this.object;
		}
		throw new AlreadyBuiltException("This object has already been built");
	}

	/**
	 * Gets the object that was built. If it has not been built yet an Exception is
	 * thrown.
	 *
	 * @return the Object that was built
	 */
	public final O getObject() {
		if (!this.building.get()) {
			throw new IllegalStateException("This object has not been built");
		}
		return this.object;
	}

	/**
	 * Subclasses should implement this to perform the build.
	 *
	 * @return the object that should be returned by #build().
	 *
	 * @throws Exception if an error occurs
	 */
	protected abstract O doBuild() throws Exception;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值