2.简单工厂模式(Simple Factory)
简单工厂模式实现原理
对象的 创建 和 使用 分离开,就是简单工厂模式。简单工厂模式又叫静态工厂方法模式,就是将对象产生的细节进行隐藏,客户端只负责调用即可。
软件开发中,开发人员不能将代码写在同一个类中,这样类越来越大,变得难以维护,因此需要将一个类中不同的功能划分多个类来完成,这就是面向对象设计原则中类的单一职责原则,简单工厂模式就是将类的职责进行细分。
抽象产品类
IProduct.java
package simpleFactory;
public interface IProduct {
void operation();
}
具体产品类
Product1.java
package simpleFactory;
public class Product1 implements IProduct {
@Override
public void operation() {
}
}
package simpleFactory;
public class Product2 implements IProduct {
@Override
public void operation() {
}
}
工厂类
Factory
package simpleFactory;
public class Factory{
//根据参数创建不同对象
public static IProduct createProduct(String productName) {
if("1".equals(productName)){
return new Product1();
}
else if("2".equals(productName)){
return new Product2();
}
return null;
}
}
简单工厂模式在翻译器中的实际应用
package simpleFactory.app;
//定义翻译接口 相当与简单工厂模式的Product
public interface Translate {
public String sayTxt(String txt);
}
package simpleFactory.app;
// 定义中文翻译的实现类 相当与简单工厂模式的Product1
public class CNTranslate implements Translate{
@Override
public String sayTxt(String txt) {
return "您好"+txt;
}
}
package simpleFactory.app;
// 定义英文翻译的实现类 相当与简单工厂模式的Product2
public class ENTranslate implements Translate{
@Override
public String sayTxt(String txt) {
return "hello" + txt;
}
}
package simpleFactory.app;
// 工厂类
public class SimpleFactory {
public Translate getTranslate(int type){
if(type == 1){
return new CNTranslate();
}
else if(type == 2){
return new ENTranslate();
}
else{
return null;
}
}
}
package simpleFactory.app;
//客户端测试类
public class Client {
public static void main (String[] args) {
SimpleFactory simpleFactory = new SimpleFactory();
Translate translate = simpleFactory.getTranslate(1);
System.out.println(translate.sayTxt("测试"));
translate = simpleFactory.getTranslate(2);
System.out.println(translate.sayTxt("测试"));
}
}
从上面代码中看出,在工厂类中有很多条件判断,为了减少判断的使用,另外一种可以通过java的反射机制
//通过反射 参数要传对象完整路径(包名+类名)
public Translate getTranslate(String type){
Translate translate = null;
try {
translate = (Translate)Class.forName(type).newInstance();
}
catch (InstantiationException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
return translate;
}
//反射形式
translate = simpleFactory.getTranslate("simpleFactory.app.CNTranslate");
System.out.println(translate.sayTxt("测试"));
translate = simpleFactory.getTranslate("simpleFactory.app.ENTranslate");
System.out.println(translate.sayTxt("测试"));
Spring就使用了工厂模式来创建bean,通过xml或者properties进行配置,下面用spring来实现上述功能,首先建立一个class.properties文件
class = simpleFactory.app.ENTranslate
在SimpleFactory类中添加代码:
//模拟spring
public Translate getTranslate(){
Translate translate = null;
try {
Properties p = new Properties();
InputStream in = null;
try {
in = SimpleFactory.class.getResourceAsStream("class.properties");
p.load(in);
}
catch (IOException e) {
e.printStackTrace();
}finally{
try {
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
translate = (Translate)Class.forName(p.getProperty("class")).newInstance();
}
catch (InstantiationException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
return translate;
}
//模拟spring
translate = simpleFactory.getTranslate();
System.out.println(translate.sayTxt("测试"));
3.工厂方法模式(Factory Method)
工厂方法模式对上个示例的改进
仍以翻译器的示例来进行说明,在上文示例的简单工厂模式中,客户端需要传入参数或者通过配置来给工厂类判断需要创建的对象,如果创建对象的初始化工作比较复杂,而且不同对象的创建又有很大不同,此时这个工厂类就变得非常庞大,此时就需要工厂方法模式,现把上文翻译器示例修改为采用工厂方法模式实现:
package FactoryMethod.app;
//定义翻译接口 相当与简单工厂模式的Product
public interface Translate {
public String sayTxt(String txt);
}
package FactoryMethod.app;
// 定义中文翻译的实现类 相当与简单工厂模式的Product1
public class CNTranslate implements Translate{
@Override
public String sayTxt(String txt) {
return "您好"+txt;
}
}
package FactoryMethod.app;
// 定义英文翻译的实现类 相当与简单工厂模式的Product2
public class ENTranslate implements Translate{
@Override
public String sayTxt(String txt) {
return "hello" + txt;
}
}
和简单工厂模式不同的是,采用工厂方法模式需要首先建立一个工厂接口类
package FactoryMethod.app;
// 工厂接口类
public interface IFactoryMethod {
Translate getTranslate();
}
package FactoryMethod.app;
// 中文翻译的工厂实现类
public class CNFactoryMethod implements IFactoryMethod{
@Override
public Translate getTranslate() {
return new CNTranslate();
}
}
package FactoryMethod.app;
// 英文翻译的工厂实现类
public class ENFactoryMethod implements IFactoryMethod{
@Override
public Translate getTranslate() {
return new ENTranslate();
}
}
package FactoryMethod.app;
// 客户端测试
public class Client {
public static void main (String[] args) {
IFactoryMethod factoryMethod = new CNFactoryMethod();
Translate translate = factoryMethod.getTranslate();
System.out.println(translate.sayTxt("测试"));
factoryMethod = new ENFactoryMethod();
translate = factoryMethod.getTranslate();
System.out.println(translate.sayTxt("测试"));
}
}
上述代码值得注意的是,如果对象的创建和初始化工作没什么大的不同,就没有必要采用工厂方法模式,直接使用简单工厂模式即可。
还有一种情况就是一个类在创建某个对象时还不知道这个对象的具体实现(即不知道IProduct里有啥方法),此时用工厂方法模式较好。
工厂方法模式的实现原理
工厂方法模式相对于简单工厂模式来说,就是把一个单一的工厂类,分成了多个具体的小工厂,并抽象出一个工厂接口,这个接口只负责定义创建的方式,至于创建的具体内容由实现它的小工厂类完成。
上图比较典型,此图作为了解:(注意这里是抽象类的继承,不是接口)
(看网上的讲法与此书的不同,个人认为《深入浅出设计模式》一书的讲法比较适合思维的扩散,且重点放在思想和设计,而网上的讲法(将工厂方法模式又分为普通工厂模式、多个工厂模式、静态工厂模式)非常冗余,比如工厂类中用一个方法创建不同对象和用多个方法创建不同对象,没有必要这么划分,将思维都固化了。所以这里我只总结了原书的讲解,网上的没有移过来。
工厂方法模式在Spring中的实际应用
在Spring中,通过配置即可实现依赖注入,然后通过工厂方法模式来创建bean。“实现必须依赖于抽象,而不是抽象依赖实现”就是“反向控制”的一种表现方式。
现在来用一个实例(通过IOC实现业务逻辑从哪种数据存储地方取得数据)说明抽象的概念:
取得数据的方式可能有3种,分别来自数据库、XML、File。若开始就是从数据库中取得数据,那么Business类中就new Sql().getData();若改成XML,则得修改业务逻辑Business类:new XML().getData();若又改成file,同理又得修改Business。这就是不好的设计,那么如何实现Business的重用呢?
答案就是IOC。由于书中此代码是用于讲解,我就不贴出,直接总结成图的形式,直观明了:
这里Business不用改变,只用修改客户端,向Business传入途径(IDataBase的实现类)。
通过接口编程,控制权在接口(父),而不是实现类(子),即控制关系的反向转换。
BeanFactory接口是Spring提供的工厂bean的标准接口,使用BeanFactory接口可以简化工厂bean的开发和配置。ApplicationContext建立在BeanFactory之上,并增加了其他功能,比如更易于同Spring AOP整合。
Spring的IOC功能实际上就是ApplicationContext组件结合BeanFactory组件共同实现的。
补充知识:Spring的依赖注入3种实现方式:接口注入、Set注入、构造注入。Set注入最为常见,此例就是Set注入。
书中讲解了Spring的AbstractApplicationContext.java
,建议去研究下源码,了解了这个类,就了解了Spring中工厂方法模式的实现原理。
附AbstractApplicationContext.java源码和注释:(很长)
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.support.ResourceEditorRegistrar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.HierarchicalMessageSource;
import org.springframework.context.LifecycleProcessor;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.context.expression.StandardBeanExpressionResolver;
import org.springframework.context.weaving.LoadTimeWeaverAware;
import org.springframework.context.weaving.LoadTimeWeaverAwareProcessor;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext, DisposableBean {
public static final String MESSAGE_SOURCE_BEAN_NAME = "messageSource";
public static final String LIFECYCLE_PROCESSOR_BEAN_NAME = "lifecycleProcessor";
public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
static {
// 加载ContextClosedEvent
ContextClosedEvent.class.getName();
}
// 定义日志
protected final Log logger = LogFactory.getLog(getClass());
private String id = ObjectUtils.identityToString(this);
private String displayName = ObjectUtils.identityToString(this);
// 定义上下文
private ApplicationContext parent;
private final List<BeanFactoryPostProcessor> beanFactoryPostProcessors = new ArrayList();
private long startupDate;
private boolean active = false;
private boolean closed = false;
private final Object activeMonitor = new Object();
private final Object startupShutdownMonitor = new Object();
private Thread shutdownHook;
private ResourcePatternResolver resourcePatternResolver;
private LifecycleProcessor lifecycleProcessor;
private MessageSource messageSource;
private ApplicationEventMulticaster applicationEventMulticaster;
private Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet();
private ConfigurableEnvironment environment;
// 无参构造方法
public AbstractApplicationContext() {
this(null);
}
// 根据传入上下文创建 AbstractApplicationContext
public AbstractApplicationContext(ApplicationContext parent) {
this.parent = parent;
this.resourcePatternResolver = getResourcePatternResolver();
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return this.id;
}
public String getApplicationName() {
return "";
}
public void setDisplayName(String displayName) {
Assert.hasLength(displayName, "Display name must not be empty");
this.displayName = displayName;
}
public String getDisplayName() {
return this.displayName;
}
public ApplicationContext getParent() {
return this.parent;
}
public ConfigurableEnvironment getEnvironment() {
if (this.environment == null) {
this.environment = createEnvironment();
}
return this.environment;
}
public void setEnvironment(ConfigurableEnvironment environment) {
this.environment = environment;
}
public AutowireCapableBeanFactory getAutowireCapableBeanFactory()
throws IllegalStateException {
return getBeanFactory();
}
public long getStartupDate() {
return this.startupDate;
}
public void publishEvent(ApplicationEvent event) {
Assert.notNull(event, "Event must not be null");
if (this.logger.isTraceEnabled()) {
this.logger.trace("Publishing event in " + getDisplayName() + ": "
+ event);
}
getApplicationEventMulticaster().multicastEvent(event);
if (this.parent != null) {
this.parent.publishEvent(event);
}
}
private ApplicationEventMulticaster getApplicationEventMulticaster()
throws IllegalStateException {
if (this.applicationEventMulticaster == null) {
throw new IllegalStateException(
"ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: "
+ this);
}
return this.applicationEventMulticaster;
}
// 根据上下文返回 LifecycleProcessor
private LifecycleProcessor getLifecycleProcessor() {
if (this.lifecycleProcessor == null) {
throw new IllegalStateException(
"LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: "
+ this);
}
return this.lifecycleProcessor;
}
protected ResourcePatternResolver getResourcePatternResolver() {
return new PathMatchingResourcePatternResolver(this);
}
public void setParent(ApplicationContext parent) {
this.parent = parent;
if (parent != null) {
Environment parentEnvironment = parent.getEnvironment();
if ((parentEnvironment instanceof ConfigurableEnvironment)) {
getEnvironment().merge(
(ConfigurableEnvironment) parentEnvironment);
}
}
}
public void addBeanFactoryPostProcessor(
BeanFactoryPostProcessor beanFactoryPostProcessor) {
this.beanFactoryPostProcessors.add(beanFactoryPostProcessor);
}
public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
return this.beanFactoryPostProcessors;
}
public void addApplicationListener(ApplicationListener<?> listener) {
if (this.applicationEventMulticaster != null) {
this.applicationEventMulticaster.addApplicationListener(listener);
} else {
this.applicationListeners.add(listener);
}
}
public Collection<ApplicationListener<?>> getApplicationListeners() {
return this.applicationListeners;
}
protected ConfigurableEnvironment createEnvironment() {
return new StandardEnvironment();
}
/* 工厂模式的具体应用
* 构建BeanFactory,注册可能感兴趣的事件,创建bean实例对象,触发被监听的事件
* */
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 上下文的前置刷新
prepareRefresh();
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 前置bean工厂
prepareBeanFactory(beanFactory);
try {
// 允许bean工厂
postProcessBeanFactory(beanFactory);
// 在上下文中反射bean工厂
invokeBeanFactoryPostProcessors(beanFactory);
// 注册bean
registerBeanPostProcessors(beanFactory);
// 初始化消息资源
initMessageSource();
// 初始化事件监听
initApplicationEventMulticaster();
// 初始化子类
onRefresh();
// 检查监听bean
registerListeners();
finishBeanFactoryInitialization(beanFactory);
// 发布事件
finishRefresh();
}
// 销毁bean
catch (BeansException ex) {
destroyBeans();
cancelRefresh(ex);
throw ex;
}
}
}
// 刷新上下文 在创建bean工厂之前刷新上下文
protected void prepareRefresh() {
// 同步监听
this.startupDate = System.currentTimeMillis();
synchronized (this.activeMonitor) {
this.active = true;
}
// 记录日志
if (this.logger.isInfoEnabled()) {
this.logger.info("Refreshing " + this);
}
//初始化属性
initPropertySources();
//验证所有属性
getEnvironment().validateRequiredProperties();
}
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Bean factory for " + getDisplayName() + ": "
+ beanFactory);
}
return beanFactory;
}
// 配置工厂资源
protected void prepareBeanFactory(
ConfigurableListableBeanFactory beanFactory) {
// bean工厂是由上下文加载
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory
.setBeanExpressionResolver(new StandardBeanExpressionResolver());
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(
this, getEnvironment()));
// 配置bean工厂的上下文
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(
this));
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory
.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
// 注册bean工厂的类型
beanFactory
.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(
ApplicationEventPublisher.class, this);
beanFactory
.registerResolvableDependency(ApplicationContext.class, this);
if (beanFactory.containsBean("loadTimeWeaver")) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(
beanFactory));
// 设置类加载器
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(
beanFactory.getBeanClassLoader()));
}
// 注册默认的bean
if (!beanFactory.containsLocalBean("environment")) {
beanFactory.registerSingleton("environment", getEnvironment());
}
// 注册单例模式的bean
if (!beanFactory.containsLocalBean("systemProperties")) {
beanFactory.registerSingleton("systemProperties", getEnvironment()
.getSystemProperties());
}
// 注册bean的系统环境
if (!beanFactory.containsLocalBean("systemEnvironment")) {
beanFactory.registerSingleton("systemEnvironment", getEnvironment()
.getSystemEnvironment());
}
}
// 实例化所有注册的bean 利用了java反射
protected void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory) {
Set<String> processedBeans = new HashSet();
if ((beanFactory instanceof BeanDefinitionRegistry)) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList();
List<BeanDefinitionRegistryPostProcessor> registryPostProcessors = new LinkedList();
for (BeanFactoryPostProcessor postProcessor : getBeanFactoryPostProcessors()) {
if ((postProcessor instanceof BeanDefinitionRegistryPostProcessor)) {
BeanDefinitionRegistryPostProcessor registryPostProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor;
registryPostProcessor
.postProcessBeanDefinitionRegistry(registry);
registryPostProcessors.add(registryPostProcessor);
} else {
regularPostProcessors.add(postProcessor);
}
}
Map<String, BeanDefinitionRegistryPostProcessor> beanMap = beanFactory
.getBeansOfType(BeanDefinitionRegistryPostProcessor.class,
true, false);
List<BeanDefinitionRegistryPostProcessor> registryPostProcessorBeans = new ArrayList(
beanMap.values());
OrderComparator.sort(registryPostProcessorBeans);
for (BeanDefinitionRegistryPostProcessor postProcessor : registryPostProcessorBeans) {
postProcessor.postProcessBeanDefinitionRegistry(registry);
}
invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(registryPostProcessorBeans,
beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
processedBeans.addAll(beanMap.keySet());
} else {
// 通过上下文实例反射工厂
invokeBeanFactoryPostProcessors(getBeanFactoryPostProcessors(),
beanFactory);
}
// 记录所有实例化的bean
String[] postProcessorNames = beanFactory.getBeanNamesForType(
BeanFactoryPostProcessor.class, true, false);
// 加载bean工厂
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList();
List<String> orderedPostProcessorNames = new ArrayList();
List<String> nonOrderedPostProcessorNames = new ArrayList();
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
if (isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(
ppName, BeanFactoryPostProcessor.class));
} else if (isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
} else {
nonOrderedPostProcessorNames.add(ppName);
}
}
}
//首先反射 BeanFactoryPostProcessors
OrderComparator.sort(priorityOrderedPostProcessors);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors,
beanFactory);
// 接着反射 BeanFactoryPostProcessors排序
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(getBean(postProcessorName,
BeanFactoryPostProcessor.class));
}
OrderComparator.sort(orderedPostProcessors);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// 最后反射其他的 BeanFactoryPostProcessors
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(getBean(postProcessorName,
BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
}
// 反射已经获取的 BeanFactoryPostProcessor
private void invokeBeanFactoryPostProcessors(
Collection<? extends BeanFactoryPostProcessor> postProcessors,
ConfigurableListableBeanFactory beanFactory) {
for (BeanFactoryPostProcessor postProcessor : postProcessors) {
postProcessor.postProcessBeanFactory(beanFactory);
}
}
// 注册bean
protected void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory) {
String[] postProcessorNames = beanFactory.getBeanNamesForType(
BeanPostProcessor.class, true, false);
// 注册 BeanPostProcessorChecker
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount()
+ 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(
beanFactory, beanProcessorTargetCount));
// 分离 BeanPostProcessors 和 PriorityOrdered
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList();
List<BeanPostProcessor> internalPostProcessors = new ArrayList();
List<String> orderedPostProcessorNames = new ArrayList();
List<String> nonOrderedPostProcessorNames = new ArrayList();
for (String ppName : postProcessorNames) {
if (isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = (BeanPostProcessor) beanFactory.getBean(
ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if ((pp instanceof MergedBeanDefinitionPostProcessor)) {
internalPostProcessors.add(pp);
}
} else if (isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
} else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// 首先注册 BeanPostProcessors
OrderComparator.sort(priorityOrderedPostProcessors);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// 其次注册根据排序的BeanPostProcessors
List<BeanPostProcessor> orderedPostProcessors = new ArrayList();
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = (BeanPostProcessor) beanFactory.getBean(
ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if ((pp instanceof MergedBeanDefinitionPostProcessor)) {
internalPostProcessors.add(pp);
}
}
OrderComparator.sort(orderedPostProcessors);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// 注册所有的 BeanPostProcessors
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList();
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = (BeanPostProcessor) beanFactory.getBean(
ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if ((pp instanceof MergedBeanDefinitionPostProcessor)) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// 最后重复注册 BeanPostProcessors
OrderComparator.sort(internalPostProcessors);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(null));
}
// 注册BeanPostProcessor
private void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory,
List<BeanPostProcessor> postProcessors) {
for (BeanPostProcessor postProcessor : postProcessors) {
beanFactory.addBeanPostProcessor(postProcessor);
}
}
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean("messageSource")) {
this.messageSource = ((MessageSource) beanFactory.getBean(
"messageSource", MessageSource.class));
if ((this.parent != null)
&& ((this.messageSource instanceof HierarchicalMessageSource))) {
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (hms.getParentMessageSource() == null) {
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
if (this.logger.isDebugEnabled()) {
this.logger.debug("Using MessageSource [" + this.messageSource
+ "]");
}
} else {
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton("messageSource", this.messageSource);
if (this.logger.isDebugEnabled()) {
this.logger
.debug("Unable to locate MessageSource with name 'messageSource': using default ["
+ this.messageSource + "]");
}
}
}
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean("applicationEventMulticaster")) {
this.applicationEventMulticaster = ((ApplicationEventMulticaster) beanFactory
.getBean("applicationEventMulticaster",
ApplicationEventMulticaster.class));
if (this.logger.isDebugEnabled()) {
this.logger.debug("Using ApplicationEventMulticaster ["
+ this.applicationEventMulticaster + "]");
}
} else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(
beanFactory);
beanFactory.registerSingleton("applicationEventMulticaster",
this.applicationEventMulticaster);
if (this.logger.isDebugEnabled()) {
this.logger
.debug("Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default ["
+ this.applicationEventMulticaster + "]");
}
}
}
protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean("lifecycleProcessor")) {
this.lifecycleProcessor = ((LifecycleProcessor) beanFactory
.getBean("lifecycleProcessor", LifecycleProcessor.class));
if (this.logger.isDebugEnabled()) {
this.logger.debug("Using LifecycleProcessor ["
+ this.lifecycleProcessor + "]");
}
} else {
DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
defaultProcessor.setBeanFactory(beanFactory);
this.lifecycleProcessor = defaultProcessor;
beanFactory.registerSingleton("lifecycleProcessor",
this.lifecycleProcessor);
if (this.logger.isDebugEnabled()) {
this.logger
.debug("Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default ["
+ this.lifecycleProcessor + "]");
}
}
}
protected void registerListeners() {
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
String[] listenerBeanNames = getBeanNamesForType(
ApplicationListener.class, true, false);
for (String lisName : listenerBeanNames) {
getApplicationEventMulticaster()
.addApplicationListenerBean(lisName);
}
}
// 完成bean工厂初始化工作
protected void finishBeanFactoryInitialization(
ConfigurableListableBeanFactory beanFactory) {
// 初始化上下文
if ((beanFactory.containsBean("conversionService"))
&& (beanFactory.isTypeMatch("conversionService",
ConversionService.class))) {
beanFactory.setConversionService((ConversionService) beanFactory
.getBean("conversionService", ConversionService.class));
}
String[] weaverAwareNames = beanFactory.getBeanNamesForType(
LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// 停止类加载器的匹配
beanFactory.setTempClassLoader(null);
// 释放配置信息
beanFactory.freezeConfiguration();
// 实例化没有延迟加载的内容
beanFactory.preInstantiateSingletons();
}
// 最后进行判断
protected void finishRefresh() {
// 初始化生命周期
initLifecycleProcessor();
// 获取生命周期
getLifecycleProcessor().onRefresh();
// 发布最终的事件
publishEvent(new ContextRefreshedEvent(this));
LiveBeansView.registerApplicationContext(this);
}
// 取消刷新
protected void cancelRefresh(BeansException ex) {
synchronized (this.activeMonitor) {
this.active = false;
}
}
public void registerShutdownHook() {
if (this.shutdownHook == null) {
this.shutdownHook = new Thread() {
public void run() {
AbstractApplicationContext.this.doClose();
}
};
Runtime.getRuntime().addShutdownHook(this.shutdownHook);
}
}
public void destroy() {
close();
}
public void close() {
synchronized (this.startupShutdownMonitor) {
doClose();
if (this.shutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
} catch (IllegalStateException ex) {
}
}
}
}
protected void doClose() {
boolean actuallyClose;
synchronized (this.activeMonitor) {
actuallyClose = (this.active) && (!this.closed);
this.closed = true;
}
if (actuallyClose) {
if (this.logger.isInfoEnabled()) {
this.logger.info("Closing " + this);
}
LiveBeansView.unregisterApplicationContext(this);
try {
publishEvent(new ContextClosedEvent(this));
} catch (Throwable ex) {
this.logger
.warn("Exception thrown from ApplicationListener handling ContextClosedEvent",
ex);
}
try {
getLifecycleProcessor().onClose();
} catch (Throwable ex) {
this.logger
.warn("Exception thrown from LifecycleProcessor on context close",
ex);
}
destroyBeans();
closeBeanFactory();
onClose();
synchronized (this.activeMonitor) {
this.active = false;
}
}
}
protected void destroyBeans() {
getBeanFactory().destroySingletons();
}
public boolean isActive() {
synchronized (this.activeMonitor) {
return this.active;
}
}
protected void assertBeanFactoryActive() {
synchronized (this.activeMonitor) {
if (!this.active) {
if (this.closed) {
throw new IllegalStateException(getDisplayName()
+ " has been closed already");
}
throw new IllegalStateException(getDisplayName()
+ " has not been refreshed yet");
}
}
}
public Object getBean(String name) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(name);
}
public <T> T getBean(String name, Class<T> requiredType)
throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(name, requiredType);
}
public <T> T getBean(Class<T> requiredType) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(requiredType);
}
public Object getBean(String name, Object... args) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(name, args);
}
public boolean containsBean(String name) {
return getBeanFactory().containsBean(name);
}
public boolean isSingleton(String name)
throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().isSingleton(name);
}
public boolean isPrototype(String name)
throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().isPrototype(name);
}
public boolean isTypeMatch(String name, Class<?> targetType)
throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().isTypeMatch(name, targetType);
}
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().getType(name);
}
public String[] getAliases(String name) {
return getBeanFactory().getAliases(name);
}
public boolean containsBeanDefinition(String beanName) {
return getBeanFactory().containsBeanDefinition(beanName);
}
public int getBeanDefinitionCount() {
return getBeanFactory().getBeanDefinitionCount();
}
public String[] getBeanDefinitionNames() {
return getBeanFactory().getBeanDefinitionNames();
}
public String[] getBeanNamesForType(Class<?> type) {
assertBeanFactoryActive();
return getBeanFactory().getBeanNamesForType(type);
}
public String[] getBeanNamesForType(Class<?> type,
boolean includeNonSingletons, boolean allowEagerInit) {
assertBeanFactoryActive();
return getBeanFactory().getBeanNamesForType(type, includeNonSingletons,
allowEagerInit);
}
public <T> Map<String, T> getBeansOfType(Class<T> type)
throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBeansOfType(type);
}
public <T> Map<String, T> getBeansOfType(Class<T> type,
boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBeansOfType(type, includeNonSingletons,
allowEagerInit);
}
public Map<String, Object> getBeansWithAnnotation(
Class<? extends Annotation> annotationType) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBeansWithAnnotation(annotationType);
}
public <A extends Annotation> A findAnnotationOnBean(String beanName,
Class<A> annotationType) {
assertBeanFactoryActive();
return getBeanFactory().findAnnotationOnBean(beanName, annotationType);
}
public BeanFactory getParentBeanFactory() {
return getParent();
}
public boolean containsLocalBean(String name) {
return getBeanFactory().containsLocalBean(name);
}
protected BeanFactory getInternalParentBeanFactory() {
return (getParent() instanceof ConfigurableApplicationContext) ? ((ConfigurableApplicationContext) getParent())
.getBeanFactory() : getParent();
}
public String getMessage(String code, Object[] args, String defaultMessage,
Locale locale) {
return getMessageSource()
.getMessage(code, args, defaultMessage, locale);
}
public String getMessage(String code, Object[] args, Locale locale)
throws NoSuchMessageException {
return getMessageSource().getMessage(code, args, locale);
}
public String getMessage(MessageSourceResolvable resolvable, Locale locale)
throws NoSuchMessageException {
return getMessageSource().getMessage(resolvable, locale);
}
private MessageSource getMessageSource() throws IllegalStateException {
if (this.messageSource == null) {
throw new IllegalStateException(
"MessageSource not initialized - call 'refresh' before accessing messages via the context: "
+ this);
}
return this.messageSource;
}
protected MessageSource getInternalParentMessageSource() {
return (getParent() instanceof AbstractApplicationContext) ? ((AbstractApplicationContext) getParent()).messageSource
: getParent();
}
public Resource[] getResources(String locationPattern) throws IOException {
return this.resourcePatternResolver.getResources(locationPattern);
}
public void start() {
getLifecycleProcessor().start();
publishEvent(new ContextStartedEvent(this));
}
public void stop() {
getLifecycleProcessor().stop();
publishEvent(new ContextStoppedEvent(this));
}
public boolean isRunning() {
return getLifecycleProcessor().isRunning();
}
public String toString() {
StringBuilder sb = new StringBuilder(getDisplayName());
sb.append(": startup date [").append(new Date(getStartupDate()));
sb.append("]; ");
ApplicationContext parent = getParent();
if (parent == null) {
sb.append("root of context hierarchy");
} else {
sb.append("parent: ").append(parent.getDisplayName());
}
return sb.toString();
}
protected void initPropertySources() {
}
protected void postProcessBeanFactory(
ConfigurableListableBeanFactory beanFactory) {
}
protected void onRefresh() throws BeansException {
}
protected void onClose() {
}
// 这个方法实现了 AbstractApplicationContext 的抽象方法 这段代码清楚的说明了BeanFactory的创建过程
protected abstract void refreshBeanFactory() throws BeansException,
IllegalStateException;
protected abstract void closeBeanFactory();
public abstract ConfigurableListableBeanFactory getBeanFactory()
throws IllegalStateException;
private class BeanPostProcessorChecker implements BeanPostProcessor {
private final ConfigurableListableBeanFactory beanFactory;
private final int beanPostProcessorTargetCount;
public BeanPostProcessorChecker(
ConfigurableListableBeanFactory beanFactory,
int beanPostProcessorTargetCount) {
this.beanFactory = beanFactory;
this.beanPostProcessorTargetCount = beanPostProcessorTargetCount;
}
public Object postProcessBeforeInitialization(Object bean,
String beanName) {
return bean;
}
public Object postProcessAfterInitialization(Object bean,
String beanName) {
if ((bean != null)
&& (!(bean instanceof BeanPostProcessor))
&& (this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount)
&& (AbstractApplicationContext.this.logger.isInfoEnabled())) {
AbstractApplicationContext.this.logger
.info("Bean '"
+ beanName
+ "' of type ["
+ bean.getClass()
+ "] is not eligible for getting processed by all BeanPostProcessors "
+ "(for example: not eligible for auto-proxying)");
}
return bean;
}
}
private class ApplicationListenerDetector implements
MergedBeanDefinitionPostProcessor {
private final Map<String, Boolean> singletonNames = new ConcurrentHashMap(
64);
private ApplicationListenerDetector() {
}
public void postProcessMergedBeanDefinition(
RootBeanDefinition beanDefinition, Class<?> beanType,
String beanName) {
if (beanDefinition.isSingleton()) {
this.singletonNames.put(beanName, Boolean.TRUE);
}
}
public Object postProcessBeforeInitialization(Object bean,
String beanName) {
return bean;
}
public Object postProcessAfterInitialization(Object bean,
String beanName) {
if ((bean instanceof ApplicationListener)) {
Boolean flag = (Boolean) this.singletonNames.get(beanName);
if (Boolean.TRUE.equals(flag)) {
AbstractApplicationContext.this
.addApplicationListener((ApplicationListener) bean);
} else if (flag == null) {
if ((AbstractApplicationContext.this.logger.isWarnEnabled())
&& (!AbstractApplicationContext.this
.containsBean(beanName))) {
AbstractApplicationContext.this.logger
.warn("Inner bean '"
+ beanName
+ "' implements ApplicationListener interface "
+ "but is not reachable for event multicasting by its containing ApplicationContext "
+ "because it does not have singleton scope. Only top-level listener beans are allowed "
+ "to be of non-singleton scope.");
}
this.singletonNames.put(beanName, Boolean.FALSE);
}
}
return bean;
}
}
}