spring源码分析-浅淡工厂模式的应用

一谈到spring,它可是集设计之大成,今天我们来浅谈一下spring中的工厂模式。第一次写关于设计模式的文章,如有纰漏,还请指正。
当然这只是冰山之一角。各位如果觉得太简单,只当路过而已 :) 。

我们都知道工厂模式是GOF23中设计模式之一,属于创建模式的一种。
而工厂模式又细分为工厂方法和抽象工厂。

简单的来说,工厂方法直接在工厂里返回所需求的实例。针对只创建一种“产品”时使用。
而抽象方法则是用在创建多个“产品”的情况下,把创建“产品”的过程延迟到了子类中,只留下了一个抽象的创建方法。

下面我们来看一下spring中ApplicationContext及子类的对于工厂方法的使用。

我们先来看一看ClassPathXmlApplicationContext的继承结构:


[img]http://dl.iteye.com/upload/attachment/275423/be0620d6-4236-3472-9bc5-f3721bae11c2.gif[/img]

在抽象类AbstractRefreshableApplicationContext中有getBeanFactory()的定义
	/**
* Subclasses must return their internal bean factory here. They should implement the
* lookup efficiently, so that it can be called repeatedly without a performance penalty.
* <p>Note: Subclasses should check whether the context is still active before
* returning the internal bean factory. The internal factory should generally be
* considered unavailable once the context has been closed.
* @return this application context's internal bean factory (never <code>null</code>)
* @throws IllegalStateException if the context does not hold an internal bean factory yet
* (usually if {@link #refresh()} has never been called) or if the context has been
* closed already
* @see #refreshBeanFactory()
* @see #closeBeanFactory()
*/
public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;

当然,此方法是其实现的接口ConfigurableApplicationContext中的一个方法。如下:

public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext, DisposableBean {
  ...
}


我们来看看ConfigurableApplicationContext 的定义 
public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle {

...

ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;

}


而getBeanFactory()方法却在AbstractRefreshableApplicationContext类中被大量的使用了,随便举一二例:
	protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
          ...
}


又如:

	protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
 ...
}


而直到其子类AbstractRefreshableApplicationContext中,才得以实现:
	@Override
public final ConfigurableListableBeanFactory getBeanFactory() {
synchronized (this.beanFactoryMonitor) {
if (this.beanFactory == null) {
throw new IllegalStateException("BeanFactory not initialized or already closed - " +
"call 'refresh' before accessing beans via the ApplicationContext");
}
return this.beanFactory;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值