循环依赖检测方法 spring源码方法

场景:checkForAliasCircle(name,alias);

this.aliasMap.put(alias,name);

A,B

B,C

当准备存入C,A时,执行checkForAliasCircle检验是否构成key-value循环

代码实现检测方式:

publicclassSimpleAliasRegistryimplementsAliasRegistry{

/**Mapfromaliastocanonicalname*/

privatefinalMap<String,String>aliasMap=newConcurrentHashMap<String,String>(16);

/**

*Determinetherawname,resolvingaliasestocanonicalnames.

*@paramnametheuser-specifiedname

*@returnthetransformedname

*/

publicStringcanonicalName(Stringname){

StringcanonicalName=name;

//Handlealiasing...

StringresolvedName;

do{

resolvedName=this.aliasMap.get(canonicalName);

if(resolvedName!=null){

canonicalName=resolvedName;

}

}

while(resolvedName!=null);

returncanonicalName;

}

/**

*Checkwhetherthegivennamepointsbacktogivenaliasasanalias

*intheotherdirection,catchingacircularreferenceupfrontand

*throwingacorrespondingIllegalStateException.

*@paramnamethecandidatename

*@paramaliasthecandidatealias

*@see#registerAlias

*/

protectedvoidcheckForAliasCircle(Stringname,Stringalias){

if(alias.equals(canonicalName(name))){

thrownewIllegalStateException("Cannotregisteralias'"+alias+

"'forname'"+name+"':Circularreference-'"+

name+"'isadirectorindirectaliasfor'"+alias+"'already");

}

}

相关推荐