checkForAliasCircle()
程序员文章站
2022-07-15 10:23:34
...
registerBeanDefinition注册bean定义的时候有一个判断bean别名的依赖问题
registerAlias
checkForAliasCircle(name, alias);
protected void checkForAliasCircle(String name, String alias) {
if (hasAlias(alias, name)) {
throw new IllegalStateException("Cannot register alias '" + alias +
"' for name '" + name + "': Circular reference - '" +
name + "' is a direct or indirect alias for '" + alias + "' already");
}
}
//之前的hasAlias方法
public boolean hasAlias(String name, String alias) {
for (Map.Entry<String, String> entry : this.aliasMap.entrySet()) {
String registeredName = entry.getValue();
if (registeredName.equals(name)) {
String registeredAlias = entry.getKey();
if (registeredAlias.equals(alias) || hasAlias(registeredAlias, alias)) {
return true;
}
}
}
return false;
}
//spring 5.3.5优化了方法,也可能更早,反正现在是这个
public boolean hasAlias(String name, String alias) {
String registeredName = this.aliasMap.get(alias);
return ObjectUtils.nullSafeEquals(registeredName, name) || (registeredName != null
&& hasAlias(name, registeredName));
}
public static boolean nullSafeEquals(@Nullable Object o1, @Nullable Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
if (o1.equals(o2)) {
return true;
}
if (o1.getClass().isArray() && o2.getClass().isArray()) {
return arrayEquals(o1, o2);
}
return false;
}
r(“2”,“1”);
r(“2”,“1”);
或者
r(“2”,“1”);
r(“3”,“2”);
r(“4”,“3”);
r(“4”,“1”);
类似这种返回true
r(“1”,“1”);
r(“3”,“1”);
这种会报错,但是已经在前面registerAlias(String name, String alias)方法中排除了
if (alias.equals(name)) {
this.aliasMap.remove(alias);
if (logger.isDebugEnabled()) {
logger.debug(“Alias definition '” + alias + “’ ignored since it points to same name”);
}
}