spring源碼分析(一)

來源:互聯網
上載者:User

標籤:circle   oid   www   ant   ...   eterm   software   res   illegal   

一、首先分析AliasRegistry介面。

  1、Alias別名,Registry註冊表,AliasRegistry別名註冊表介面。

  2、共有四個方法,註冊別名,判斷是否別名,擷取別名數組,移除別名。

  3、我自己試著寫了一個這個介面的實作類別:

package com.lzh.spring.test;import java.util.ArrayList;import java.util.Hashtable;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Map.Entry;import org.springframework.core.AliasRegistry;/** * 別名註冊表介面的實現 * @author LiaoZhengHan * @date 2018年8月29日 */public class MyAliasRegistry implements AliasRegistry{        private Map<String, String> aliasMap = new Hashtable<>();    @Override    public void registerAlias(String name, String alias) {                if (isAlias(alias)) {            throw new IllegalStateException();        }                aliasMap.put(alias, name);    }    @Override    public void removeAlias(String alias) {        aliasMap.remove(alias);    }    @Override    public boolean isAlias(String name) {        return aliasMap.containsKey(name);    }    @Override    public String[] getAliases(String name) {                List<String> aliases = new ArrayList<>();        Iterator<Entry<String, String>> it = aliasMap.entrySet().iterator();        Entry<String, String> entry = null;        while (it.hasNext()) {            entry = it.next();            if (entry.getValue().equals(name)) {                aliases.add(entry.getKey());            }        }        String[] array = new String[aliases.size()];        return aliases.toArray(array);    }}

 

/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.springframework.core;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import org.springframework.util.Assert;import org.springframework.util.StringUtils;import org.springframework.util.StringValueResolver;/** * Simple implementation of the {@link AliasRegistry} interface. * Serves as base class for * {@link org.springframework.beans.factory.support.BeanDefinitionRegistry} * implementations. * * @author Juergen Hoeller * @since 2.5.2 */public class SimpleAliasRegistry implements AliasRegistry {    /** Map from alias to canonical name */    private final Map<String, String> aliasMap = new ConcurrentHashMap<String, String>(16);    @Override    public void registerAlias(String name, String alias) {        Assert.hasText(name, "‘name‘ must not be empty");        Assert.hasText(alias, "‘alias‘ must not be empty");        if (alias.equals(name)) {            this.aliasMap.remove(alias);        }        else {            if (!allowAliasOverriding()) {                String registeredName = this.aliasMap.get(alias);                if (registeredName != null && !registeredName.equals(name)) {                    throw new IllegalStateException("Cannot register alias ‘" + alias + "‘ for name ‘" +                            name + "‘: It is already registered for name ‘" + registeredName + "‘.");                }            }            checkForAliasCircle(name, alias);            this.aliasMap.put(alias, name);        }    }    /**     * Return whether alias overriding is allowed.     * Default is {@code true}.     */    protected boolean allowAliasOverriding() {        return true;    }    @Override    public void removeAlias(String alias) {        String name = this.aliasMap.remove(alias);        if (name == null) {            throw new IllegalStateException("No alias ‘" + alias + "‘ registered");        }    }    @Override    public boolean isAlias(String name) {        return this.aliasMap.containsKey(name);    }    @Override    public String[] getAliases(String name) {        List<String> result = new ArrayList<String>();        synchronized (this.aliasMap) {            retrieveAliases(name, result);        }        return StringUtils.toStringArray(result);    }    /**     * Transitively retrieve all aliases for the given name.     * @param name the target name to find aliases for     * @param result the resulting aliases list     */    private void retrieveAliases(String name, List<String> result) {        for (Map.Entry<String, String> entry : this.aliasMap.entrySet()) {            String registeredName = entry.getValue();            if (registeredName.equals(name)) {                String alias = entry.getKey();                result.add(alias);                retrieveAliases(alias, result);            }        }    }    /**     * Resolve all alias target names and aliases registered in this     * factory, applying the given StringValueResolver to them.     * <p>The value resolver may for example resolve placeholders     * in target bean names and even in alias names.     * @param valueResolver the StringValueResolver to apply     */    public void resolveAliases(StringValueResolver valueResolver) {        Assert.notNull(valueResolver, "StringValueResolver must not be null");        synchronized (this.aliasMap) {            Map<String, String> aliasCopy = new HashMap<String, String>(this.aliasMap);            for (String alias : aliasCopy.keySet()) {                String registeredName = aliasCopy.get(alias);                String resolvedAlias = valueResolver.resolveStringValue(alias);                String resolvedName = valueResolver.resolveStringValue(registeredName);                if (resolvedAlias.equals(resolvedName)) {                    this.aliasMap.remove(alias);                }                else if (!resolvedAlias.equals(alias)) {                    String existingName = this.aliasMap.get(resolvedAlias);                    if (existingName != null && !existingName.equals(resolvedName)) {                        throw new IllegalStateException(                                "Cannot register resolved alias ‘" + resolvedAlias + "‘ (original: ‘" + alias +                                "‘) for name ‘" + resolvedName + "‘: It is already registered for name ‘" +                                registeredName + "‘.");                    }                    checkForAliasCircle(resolvedName, resolvedAlias);                    this.aliasMap.remove(alias);                    this.aliasMap.put(resolvedAlias, resolvedName);                }                else if (!registeredName.equals(resolvedName)) {                    this.aliasMap.put(alias, resolvedName);                }            }        }    }    /**     * Determine the raw name, resolving aliases to canonical names.     * @param name the user-specified name     * @return the transformed name     */    public String canonicalName(String name) {        String canonicalName = name;        // Handle aliasing...        String resolvedName;        do {            resolvedName = this.aliasMap.get(canonicalName);            if (resolvedName != null) {                canonicalName = resolvedName;            }        }        while (resolvedName != null);        return canonicalName;    }    /**     * Check whether the given name points back to given alias as an alias     * in the other direction, catching a circular reference upfront and     * throwing a corresponding IllegalStateException.     * @param name the candidate name     * @param alias the candidate alias     * @see #registerAlias     */    protected void checkForAliasCircle(String name, String alias) {        if (alias.equals(canonicalName(name))) {            throw new IllegalStateException("Cannot register alias ‘" + alias +                    "‘ for name ‘" + name + "‘: Circular reference - ‘" +                    name + "‘ is a direct or indirect alias for ‘" + alias + "‘ already");        }    }}

 

 


spring源碼分析(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.