Spinrg IoC-IoC完善
# 一、工厂体系扩展
之前定义的 AutowireCapableBeanFactory
,是在通用的AbstractBeanFactory
基础上,加上了处理注解的逻辑,现在我们需要对整个工厂体系进行扩展。
# 1、Bean定义集合管理
解析XML的时候,会把XML中定义的Bean解析到内存Bean定义集合中,我们首先对Bean定义集合进行管理,提供一些常用的管理方法。
public interface ListableBeanFactory extends BeanFactory {
boolean containsBeanDefinition(String beanName);
int getBeanDefinitionCount();
String[] getBeanDefinitionNames();
String[] getBeanNamesForType(Class<?> type);
<T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException;
}
# 2、Bean管理
之前我们定义了一个SingletonBeanRegistry
用来管理所有的单例Bean,现在除了对Bean的管理,我们还要额外扩展对Bean处理器的管理。
public interface ConfigurableBeanFactory extends BeanFactory, SingletonBeanRegistry {
String SCOPE_SINGLETON = "singleton";
String SCOPE_PROTOTYPE = "prototype";
void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);
int getBeanPostProcessorCount();
void registerDependentBean(String beanName, String dependentBeanName);
String[] getDependentBeans(String beanName);
String[] getDependenciesForBean(String beanName);
}
接着,我们把 AutowireCapableBeanFactory、ListableBeanFactory 和 ConfigurableBeanFactory 这些接口合并在一起。
public interface ConfigurableListableBeanFactory extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory {
}
由于使用了上述接口去整合其他接口,需要对部分接口做调整:
public interface AutowireCapableBeanFactory extends BeanFactory {
int AUTOWIRE_NO = 0;
int AUTOWIRE_BY_NAME = 1;
int AUTOWIRE_BY_TYPE = 2;
Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException;
Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException;
}
新增一个抽象类AbstractAutowireCapableBeanFactory
来实现AutowireCapableBeanFactory
原有的注解处理业务 :
public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {
private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
this.beanPostProcessors.remove(beanPostProcessor);
this.beanPostProcessors.add(beanPostProcessor);
}
public int getBeanPostProcessorCount() {
return this.beanPostProcessors.size();
}
public List<BeanPostProcessor> getBeanPostProcessors() {
return this.beanPostProcessors;
}
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
beanProcessor.setBeanFactory(this);
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
beanProcessor.setBeanFactory(this);
result = beanProcessor.postProcessAfterInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
}
# 二、环境因素
除了给IoC容器工厂体系进行完善之外,还需要给容器添加一些环境因素,使一些容器整体所需要的属性有个地方存储访问。
PropertyResolver接口
public interface PropertyResolver {
boolean containsProperty(String key);
String getProperty(String key);
String getProperty(String key, String defaultValue);
<T> T getProperty(String key, Class<T> targetType);
<T> T getProperty(String key, Class<T> targetType, T defaultValue);
<T> Class<T> getPropertyAsClass(String key, Class<T> targetType);
String getRequiredProperty(String key) throws IllegalStateException;
<T> T getRequiredProperty(String key, Class<T> targetType) throws
IllegalStateException;
String resolvePlaceholders(String text);
String resolveRequiredPlaceholders(String text) throws
IllegalArgumentException;
}
Environment接口
public interface Environment extends PropertyResolver {
String[] getActiveProfiles();
String[] getDefaultProfiles();
boolean acceptsProfiles(String... profiles);
}
EnvironmentCapable接口
public interface EnvironmentCapable {
Environment getEnvironment();
}
# 三、Ioc引擎
在第一节中,我们为了扩展工厂体系,定义了几个接口,现在我们就需要去具体实现这些接口:
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{
@Override
public int getBeanDefinitionCount() {
return this.beanDefinitions.size();
}
@Override
public String[] getBeanDefinitionNames() {
return (String[]) this.beanDefinitionNames.toArray();
}
@Override
public String[] getBeanNamesForType(Class<?> type) {
List<String> result = new ArrayList<>();
for (String beanName : this.beanDefinitionNames) {
boolean matchFound = false;
BeanDefinition mbd = this.getBeanDefinition(beanName);
Class<?> classToMatch = mbd.getClass();
if (type.isAssignableFrom(classToMatch)) {
matchFound = true;
}
else {
matchFound = false;
}
if (matchFound) {
result.add(beanName);
}
}
return (String[]) result.toArray();
}
@SuppressWarnings("unchecked")
@Override
public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
String[] beanNames = getBeanNamesForType(type);
Map<String, T> result = new LinkedHashMap<>(beanNames.length);
for (String beanName : beanNames) {
Object beanInstance = getBean(beanName);
result.put(beanName, (T) beanInstance);
}
return result;
}
}
# 四、事件机制
接着来完善事件机制,需要实现事件一旦发布,监听者就能够收到事件。
ApplicationEvent
实现事件的监听
public class ApplicationEvent extends EventObject {
private static final long serialVersionUID = 1L;
protected String msg = null;
public ApplicationEvent(Object arg0) {
super(arg0);
this.msg = arg0.toString();
}
}
ApplicationListener
public class ApplicationListener implements EventListener {
void onApplicationEvent(ApplicationEvent event) {
System.out.println(event.toString());
}
}
**ApplicationEventPublisher **
实现事件发布
public interface ApplicationEventPublisher {
void publishEvent(ApplicationEvent event);
void addApplicationListener(ApplicationListener listener);
}
ContextRefreshEvent
上下文事件刷新
public class ContextRefreshEvent extends ApplicationEvent {
private static final long serialVersionUID = 1L;
public ContextRefreshEvent(Object arg0) {
super(arg0);
}
public String toString() {
return this.msg;
}
}
SimpleApplicationEventPublisher
public class SimpleApplicationEventPublisher implements ApplicationEventPublisher {
List<ApplicationListener> listeners = new ArrayList<>();
@Override
public void publishEvent(ApplicationEvent event) {
for (ApplicationListener listener : listeners) {
listener.onApplicationEvent(event);
}
}
@Override
public void addApplicationListener(ApplicationListener listener) {
this.listeners.add(listener);
}
}
# 五、ApplicationContext
现在我们需要抽象一个新的上下文,来整合上面我们所实现的环境因素、事件机制等功能。
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, ConfigurableBeanFactory, ApplicationEventPublisher {
String getApplicationName();
long getStartupDate();
ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
void setEnvironment(Environment environment);
Environment getEnvironment();
void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor);
void refresh() throws BeansException, IllegalStateException;
void close();
boolean isActive();
}
上下文接口具体实现
public abstract class AbstractApplicationContext implements ApplicationContext {
private Environment environment;
private final List<BeanFactoryPostProcessor> beanFactoryPostProcessors = new ArrayList<>();
private long startupDate;
private final AtomicBoolean active = new AtomicBoolean();
private final AtomicBoolean closed = new AtomicBoolean();
private ApplicationEventPublisher applicationEventPublisher;
@Override
public Object getBean(String beanName) throws BeansException {
return getBeanFactory().getBean(beanName);
}
@Override
public Boolean containsBean(String name) {
return getBeanFactory().containsBean(name);
}
// public void registerBean(String beanName, Object obj) {
// getBeanFactory().registerBean(beanName, obj);
// }
@Override
public boolean isSingleton(String name) {
return getBeanFactory().isSingleton(name);
}
@Override
public boolean isPrototype(String name) {
return getBeanFactory().isPrototype(name);
}
@Override
public Class<?> getType(String name) {
return getBeanFactory().getType(name);
}
public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
return this.beanFactoryPostProcessors;
}
public void refresh() throws BeansException, IllegalStateException {
postProcessBeanFactory(getBeanFactory());
registerBeanPostProcessors(getBeanFactory());
initApplicationEventPublisher();
onRefresh();
registerListeners();
finishRefresh();
}
abstract void registerListeners();
abstract void initApplicationEventPublisher();
abstract void postProcessBeanFactory(ConfigurableListableBeanFactory bf);
abstract void registerBeanPostProcessors(ConfigurableListableBeanFactory bf);
abstract void onRefresh();
abstract void finishRefresh();
@Override
public void registerSingleton(String beanName, Object singletonObject) {
getBeanFactory().registerSingleton(beanName, singletonObject);
}
@Override
public Object getSingleton(String beanName) {
return getBeanFactory().getSingleton(beanName);
}
@Override
public boolean containsSingleton(String beanName) {
return getBeanFactory().containsSingleton(beanName);
}
@Override
public String[] getSingletonNames() {
return getBeanFactory().getSingletonNames();
}
@Override
public boolean containsBeanDefinition(String beanName) {
return getBeanFactory().containsBeanDefinition(beanName);
}
@Override
public int getBeanDefinitionCount() {
return getBeanFactory().getBeanDefinitionCount();
}
@Override
public String[] getBeanDefinitionNames() {
return getBeanFactory().getBeanDefinitionNames();
}
@Override
public String[] getBeanNamesForType(Class<?> type) {
return getBeanFactory().getBeanNamesForType(type);
}
@Override
public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
return getBeanFactory().getBeansOfType(type);
}
@Override
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
getBeanFactory().addBeanPostProcessor(beanPostProcessor);
}
@Override
public int getBeanPostProcessorCount() {
return getBeanFactory().getBeanPostProcessorCount();
}
@Override
public void registerDependentBean(String beanName, String dependentBeanName) {
getBeanFactory().registerDependentBean(beanName, dependentBeanName);
}
@Override
public String[] getDependentBeans(String beanName) {
return getBeanFactory().getDependentBeans(beanName);
}
@Override
public String[] getDependenciesForBean(String beanName) {
return getBeanFactory().getDependenciesForBean(beanName);
}
@Override
public String getApplicationName() {
return "";
}
@Override
public long getStartupDate() {
return this.startupDate;
}
@Override
public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@Override
public Environment getEnvironment() {
return this.environment;
}
@Override
public void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor) {
this.beanFactoryPostProcessors.add(postProcessor);
}
@Override
public void close() {
}
@Override
public boolean isActive() {
return true;
}
public ApplicationEventPublisher getApplicationEventPublisher() {
return applicationEventPublisher;
}
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
}
上下文解析
public class ClassPathXmlApplicationContext extends AbstractApplicationContext{
DefaultListableBeanFactory beanFactory;
private final List<BeanFactoryPostProcessor> beanFactoryPostProcessors =
new ArrayList<BeanFactoryPostProcessor>();
public ClassPathXmlApplicationContext(String fileName){
this(fileName, true);
}
public ClassPathXmlApplicationContext(String fileName, boolean isRefresh){
Resource res = new ClassPathXmlResource(fileName);
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf);
reader.loadBeanDefinitions(res);
this.beanFactory = bf;
if (isRefresh) {
try {
refresh();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (BeansException e) {
e.printStackTrace();
}
}
}
@Override
void registerListeners() {
ApplicationListener listener = new ApplicationListener();
this.getApplicationEventPublisher().addApplicationListener(listener);
}
@Override
void initApplicationEventPublisher() {
ApplicationEventPublisher aep = new SimpleApplicationEventPublisher();
this.setApplicationEventPublisher(aep);
}
@Override
void postProcessBeanFactory(ConfigurableListableBeanFactory bf) {
}
@Override
void registerBeanPostProcessors(ConfigurableListableBeanFactory bf) {
this.beanFactory.addBeanPostProcessor(new AutowiredAnnotationBeanPostProcessor());
}
@Override
void onRefresh() {
this.beanFactory.refresh();
}
@Override
public ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException {
return this.beanFactory;
}
@Override
public void addApplicationListener(ApplicationListener listener) {
this.getApplicationEventPublisher().addApplicationListener(listener);
}
@Override
void finishRefresh() {
publishEvent(new ContextRefreshEvent("Context Refreshed..."));
}
@Override
public void publishEvent(ApplicationEvent event) {
this.getApplicationEventPublisher().publishEvent(event);
}
@Override
public void registerBean(String beanName, Object obj) {
}
}