StaticListableBeanFactory分析

StaticListableBeanFactory

 

此类为org.springframework.beans.factory.BeanFactory的一个实现类

只允许注册已经存在的单例实例,不支持prototype和aliases

 

该类实现了ListableBeanFactory 也就是允许遍历得到BeanFactory保存的bean实体

 

public class StaticListableBeanFactory implements ListableBeanFactory {

	/** Map from bean name to bean instance */
	private final Map<String, Object> beans = new HashMap<String, Object>();
	
	/**
	 * Add a new singleton bean.
	 * Will overwrite any existing instance for the given name.
	 * @param name the name of the bean
	 * @param bean the bean instance
	 */
	public void addBean(String name, Object bean) {
		this.beans.put(name, bean);
	}


	//---------------------------------------------------------------------
	// 以下的内容实现了BeanFactory接口
	//---------------------------------------------------------------------

	// 通过名字获取Bean
	// 这里根据需要得到的bean是否是FactoryBean做了判断
	// 假设输入的name是一个FactoryBean的名字
	// 若输入的名字是"&name"那么返回FactoryBean类本身的实例
	// 不然若输入的是"name" 那么返回FactoryBean类的实例所管理的实例
	public Object getBean(String name) throws BeansException {
	    // 这个是用来获取beanName的 FactoryBean的输入若为"&name"的话会变为"name"
		String beanName = BeanFactoryUtils.transformedBeanName(name);
		// 通过名字获取bean
		Object bean = this.beans.get(beanName);

		// 如果bean为空则抛出异常
		if (bean == null) {
			throw new NoSuchBeanDefinitionException(beanName,
					"Defined beans are [" + StringUtils.collectionToCommaDelimitedString(this.beans.keySet()) + "]");
		}

		// 如果用了& 开头 但是这个名字对应的bean不是一个FactoryBean 则会抛出异常
		if (BeanFactoryUtils.isFactoryDereference(name) && !(bean instanceof FactoryBean)) {
			throw new BeanIsNotAFactoryException(beanName, bean.getClass());
		}
        
		// 若得到的bean是FactoryBean 并且不是以&开头的 那么返回该FactoryBean负责管理的实例
		if (bean instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
			try {
				return ((FactoryBean) bean).getObject();
			}
			catch (Exception ex) {
				throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
			}
		}
		else {
			return bean;
		}
	}
	
	// 调用上面的方法 然后进行类型判断 如果得到的bean的类型是requiredType的类(或者子类)则返回
	@SuppressWarnings("unchecked")
	public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
		Object bean = getBean(name);
		// 需要的类型为null就属于所有都匹配 
		// 不为null并且类型又不匹配就抛出异常
		if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) {
			throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
		}
		return (T) bean;
	}
	
	    // 获得requiredType类型的Bean实例
	public <T> T getBean(Class<T> requiredType) throws BeansException {
		//得到bean的name数组
		String[] beanNames = getBeanNamesForType(requiredType);
		if (beanNames.length == 1) {、
		// 调用以上方法进行判断
			return getBean(beanNames[0], requiredType);
		}
		else if (beanNames.length > 1) {
			throw new NoUniqueBeanDefinitionException(requiredType, beanNames);
		}
		else {
			throw new NoSuchBeanDefinitionException(requiredType);
		}
	}

	// 这个方法就是个摆设 在这个类里不支持
	public Object getBean(String name, Object... args) throws BeansException {
		if (args != null) {
			throw new UnsupportedOperationException(
					"StaticListableBeanFactory does not support explicit bean creation arguments)");
		}
		return getBean(name);
	}

	public boolean containsBean(String name) {
		return this.beans.containsKey(name);
	}

	// 判断bean是否单例(这里只对FactoryBean有效)
	public boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
		Object bean = getBean(name);
		// In case of FactoryBean, return singleton status of created object.
		return (bean instanceof FactoryBean && ((FactoryBean) bean).isSingleton());
	}
    
	// 判断bean是否Prototype(这里只对FactoryBean有效)
	public boolean isPrototype(String name) throws NoSuchBeanDefinitionException {
		Object bean = getBean(name);
		// In case of FactoryBean, return prototype status of created object.
		return ((bean instanceof SmartFactoryBean && ((SmartFactoryBean) bean).isPrototype()) ||
				(bean instanceof FactoryBean && !((FactoryBean) bean).isSingleton()));
	}

	public boolean isTypeMatch(String name, Class targetType) throws NoSuchBeanDefinitionException {
		Class type = getType(name);
		return (targetType == null || (type != null && targetType.isAssignableFrom(type)));
	}

	// 获得输入name的bean的类型(和以上getBean(String name)相似)
	public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
		String beanName = BeanFactoryUtils.transformedBeanName(name);

		Object bean = this.beans.get(beanName);
		if (bean == null) {
			throw new NoSuchBeanDefinitionException(beanName,
					"Defined beans are [" + StringUtils.collectionToCommaDelimitedString(this.beans.keySet()) + "]");
		}

		if (bean instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
			// If it's a FactoryBean, we want to look at what it creates, not the factory class.
			return ((FactoryBean) bean).getObjectType();
		}
		return bean.getClass();
	}

	// 这个方法没什么意义
	public String[] getAliases(String name) {
		return new String[0];
	}


	//---------------------------------------------------------------------
	// Implementation of ListableBeanFactory interface
	//---------------------------------------------------------------------

	// 以下的BeanDefinition就是Map中的key
	
	public boolean containsBeanDefinition(String name) {
		return this.beans.containsKey(name);
	}

	public int getBeanDefinitionCount() {
		return this.beans.size();
	}

	public String[] getBeanDefinitionNames() {
		return StringUtils.toStringArray(this.beans.keySet());
	}

	public String[] getBeanNamesForType(Class type) {
		return getBeanNamesForType(type, true, true);
	}

	// includeNonSingletons这个参数在这边没什么用
	public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean includeFactoryBeans) {
	    // 这个类是否是FactoryBean的子类
		boolean isFactoryType = (type != null && FactoryBean.class.isAssignableFrom(type));
		List<String> matches = new ArrayList<String>();
		// 遍历所有的名字
		for (String name : this.beans.keySet()) {
			Object beanInstance = this.beans.get(name);
			// 如果按照名字得到的是一个FactoryBean并且type不是Factory类型的话就执行(获取BeanFactory管理的实例)
			if (beanInstance instanceof FactoryBean && !isFactoryType) {
			    // 是否包括FactoryBean
				if (includeFactoryBeans) {
				    // 得到FactoryBean管理的实例的类型
					Class objectType = ((FactoryBean) beanInstance).getObjectType();
					if (objectType != null && (type == null || type.isAssignableFrom(objectType))) {
						matches.add(name);
					}
				}
			}
			else {
				if (type == null || type.isInstance(beanInstance)) {
					matches.add(name);
				}
			}
		}
		return StringUtils.toStringArray(matches);
	}

	public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
		return getBeansOfType(type, true, true);
	}

	@SuppressWarnings("unchecked")
	public <T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean includeFactoryBeans)
			throws BeansException {

		boolean isFactoryType = (type != null && FactoryBean.class.isAssignableFrom(type));
		Map<String, T> matches = new HashMap<String, T>();

		for (Map.Entry<String, Object> entry : beans.entrySet()) {
			String beanName = entry.getKey();
			Object beanInstance = entry.getValue();
			// Is bean a FactoryBean?
			if (beanInstance instanceof FactoryBean && !isFactoryType) {
				if (includeFactoryBeans) {
					// Match object created by FactoryBean.
					FactoryBean factory = (FactoryBean) beanInstance;
					Class objectType = factory.getObjectType();
					if ((includeNonSingletons || factory.isSingleton()) &&
							objectType != null && (type == null || type.isAssignableFrom(objectType))) {
						matches.put(beanName, getBean(beanName, type));
					}
				}
			}
			else {
				if (type == null || type.isInstance(beanInstance)) {
					// If type to match is FactoryBean, return FactoryBean itself.
					// Else, return bean instance.
					if (isFactoryType) {
						beanName = FACTORY_BEAN_PREFIX + beanName;
					}
					matches.put(beanName, (T) beanInstance);
				}
			}
		}
		return matches;
	}

	// 返回带有特定Annotation的对象
	public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType)
			throws BeansException {

		Map<String, Object> results = new LinkedHashMap<String, Object>();
		for (String beanName : this.beans.keySet()) {
			if (findAnnotationOnBean(beanName, annotationType) != null) {
				results.put(beanName, getBean(beanName));
			}
		}
		return results;
	}

	public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) {
	     // 这个会去搜索所给类型(以及实现的接口和父类)是否有给定的annotationType
		return AnnotationUtils.findAnnotation(getType(beanName), annotationType);
	}

}

 

你可能感兴趣的:(beanfactory)