AbstractSecurityBuilder
是Spring 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;
}