privatestaticvoidinitializeStrategy(){if(MODE_PRE_INITIALIZED.equals(strategyName)){Assert.state(strategy !=null,"When using "+MODE_PRE_INITIALIZED+", setContextHolderStrategy must be called with the fully constructed strategy");return;}//如果没有设置过使用的策略,就默认使用ThreadLocal作为存储策略if(!StringUtils.hasText(strategyName)){// Set default
strategyName =MODE_THREADLOCAL;}//使用ThreadLocal作为线程级别安全上下文存储策略if(strategyName.equals(MODE_THREADLOCAL)){
strategy =newThreadLocalSecurityContextHolderStrategy();return;}//使用InheritableThreadLocal作为线程级别安全上下文存储策略if(strategyName.equals(MODE_INHERITABLETHREADLOCAL)){
strategy =newInheritableThreadLocalSecurityContextHolderStrategy();return;}//使用Global作为线程级别安全上下文存储策略if(strategyName.equals(MODE_GLOBAL)){
strategy =newGlobalSecurityContextHolderStrategy();return;}//尝试加载自定义的线程级别安全上下文存储策略try{Class<?> clazz =Class.forName(strategyName);Constructor<?> customStrategy = clazz.getConstructor();
strategy =(SecurityContextHolderStrategy) customStrategy.newInstance();}catch(Exception ex){ReflectionUtils.handleReflectionException(ex);}}
publicfinalclassListeningSecurityContextHolderStrategyimplementsSecurityContextHolderStrategy{......privatefinalCollection<SecurityContextChangedListener> listeners;privatefinalSecurityContextHolderStrategy delegate;@OverridepublicvoidclearContext(){SecurityContext from =getContext();this.delegate.clearContext();publish(from,null);}@OverridepublicvoidsetContext(SecurityContext context){SecurityContext from =getContext();this.delegate.setContext(context);publish(from, context);}......}