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

被折叠的 条评论
为什么被折叠?



