Spring Security ObjectPostProcessor解析

顶层接口

  • org.springframework.security.config.annotation.ObjectPostProcessor
    SecurityBuilder 的抽象实现AbstractConfiguredSecurityBuilder中被引入。
    并且通过构造函数入参被设置并且构造函数为protected只能被子类实例化。

protected AbstractConfiguredSecurityBuilder(
            ObjectPostProcessor<Object> objectPostProcessor) {
        this(objectPostProcessor, false);
    }
protected AbstractConfiguredSecurityBuilder(
            ObjectPostProcessor<Object> objectPostProcessor,
            boolean allowConfigurersOfSameType) {
        Assert.notNull(objectPostProcessor, "objectPostProcessor cannot be null");
        this.objectPostProcessor = objectPostProcessor;
        this.allowConfigurersOfSameType = allowConfigurersOfSameType;
    }
  • ObjectPostProcessor

public interface ObjectPostProcessor<T> {

    //仅有一个方法用于初始化修改后的返回修改后的对象,我们来看看它的具体实现
    <O extends T> O postProcess(O object);
}
  • AutowireBeanFactoryObjectPostProcessor

//此类被final修饰,无法继承,并且此处实现了SmartInitializingSingleton该接口
//需实现afterSingletonsInstantiated,可以对bean初始化时做一些其它的事情。
//并实现了DisposableBean,即销毁时需要自己处理。
final class AutowireBeanFactoryObjectPostProcessor
        implements ObjectPostProcessor<Object>, DisposableBean, SmartInitializingSingleton {
    private final Log logger = LogFactory.getLog(getClass());
    //通过此接口扩展使Spring框架之外的程序,具有自动装配的功能。
    private final AutowireCapableBeanFactory autowireBeanFactory;
    private final List<DisposableBean> disposableBeans = new ArrayList<>();
    private final List<SmartInitializingSingleton> smartSingletons = new ArrayList<>();

    public AutowireBeanFactoryObjectPostProcessor(
            AutowireCapableBeanFactory autowireBeanFactory) {
        Assert.notNull(autowireBeanFactory, "autowireBeanFactory cannot be null");
        this.autowireBeanFactory = autowireBeanFactory;
    }
    //ObjectPostProcessor接口的方法实现。
    @SuppressWarnings("unchecked")
    public <T> T postProcess(T object) {
        if (object == null) {
            return null;
        }
        T result = null;
        try {
        //通过AutowireCapableBeanFactory 的初始化方法将对象交给spring 管理
            result = (T) this.autowireBeanFactory.initializeBean(object,
                    object.toString());
        }
        catch (RuntimeException e) {
            Class<?> type = object.getClass();
            throw new RuntimeException(
                    "Could not postProcess " + object + " of type " + type, e);
        }
        //通过调用给定Bean的after-instantiation及post-processing接口,对bean进行配置
        this.autowireBeanFactory.autowireBean(object);
        //判断当前bean是否实现DisposableBean 接口如果实现就加入disposableBeans容器备用
        if (result instanceof DisposableBean) {
            this.disposableBeans.add((DisposableBean) result);
        }
        //同上
        if (result instanceof SmartInitializingSingleton) {
            this.smartSingletons.add((SmartInitializingSingleton) result);
        }
        return result;
    }

    //单例实例化之后处理,即传入的对象需要实现afterSingletonsInstantiated接口
    //处理在postProcess阶段存入smartSingletons的实例
    @Override
    public void afterSingletonsInstantiated() {
        for (SmartInitializingSingleton singleton : smartSingletons) {
            singleton.afterSingletonsInstantiated();
        }
    }

    //销毁之前存入disposableBeans的需销毁对象
    public void destroy() throws Exception {
        for (DisposableBean disposable : this.disposableBeans) {
            try {
                disposable.destroy();
            }
            catch (Exception error) {
                this.logger.error(error);
            }
        }
    }

}

以上对象使用@Bean方式配置,在ObjectPostProcessorConfiguration中注入了


@Configuration
public class ObjectPostProcessorConfiguration {

    @Bean
    public ObjectPostProcessor<Object> objectPostProcessor(
            AutowireCapableBeanFactory beanFactory) {
        return new AutowireBeanFactoryObjectPostProcessor(beanFactory);
    }
}

ObjectPostProcessorConfiguration 在 AuthenticationConfiguration时被@Import进来。

@Import(ObjectPostProcessorConfiguration.class)
public class AuthenticationConfiguration

而 AuthenticationConfiguration则是通过@EnableGlobalAuthentication 注解导入,这个注解又是被@EnableWebSecurity 注解导入。

@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = { java.lang.annotation.ElementType.TYPE })
@Documented
@Import({ WebSecurityConfiguration.class,
        SpringWebMvcImportSelector.class,
        OAuth2ImportSelector.class })
@EnableGlobalAuthentication
@Configuration
public @interface EnableWebSecurity {

接着我们来看它的另一个实现CompositeObjectPostProcessor

private static final class CompositeObjectPostProcessor implements
            ObjectPostProcessor<Object> {
            //定义一个容器装ObjectPostProcessor对象
        private List<ObjectPostProcessor<? extends Object>> postProcessors = new ArrayList<ObjectPostProcessor<?>>();

        @SuppressWarnings({ "rawtypes", "unchecked" })
        public Object postProcess(Object object) {
            for (ObjectPostProcessor opp : postProcessors) {
                Class<?> oppClass = opp.getClass();
                //泛型解析器
                Class<?> oppType = GenericTypeResolver.resolveTypeArgument(oppClass,
                        ObjectPostProcessor.class);
                //判断该泛型对象是否与传入对象相对应如果对应则执行该对象的postProcess方法
                if (oppType == null || oppType.isAssignableFrom(object.getClass())) {
                    object = opp.postProcess(object);
                }
            }
            return object;
        }

        //往容器中添加ObjectPostProcessor对象并根据Ordered注解进行排序返回是否添加成功
        private boolean addObjectPostProcessor(
                ObjectPostProcessor<? extends Object> objectPostProcessor) {
            boolean result = this.postProcessors.add(objectPostProcessor);
            Collections.sort(postProcessors, AnnotationAwareOrderComparator.INSTANCE);
            return result;
        }
    }

CompositeObjectPostProcessor 是SecurityConfigurerAdapter 的一个静态内部类,仅用来返回对象使用,这边是将原对象传进去,执行对象的postProcess做一些修改之后在把对象返回回

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值