📄 abstractapplicationcontext.java
字号:
// instantiate singletons this late to allow them to access the message source
beanFactory.preInstantiateSingletons();
// last step: publish corresponding event
publishEvent(new ContextRefreshedEvent(this));
}
/**
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for registering special
* BeanPostProcessors etc in certain ApplicationContext implementations.
* @param beanFactory the bean factory used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
/**
* Instantiate and invoke all registered BeanFactoryPostProcessor beans,
* respecting explicit order if given.
* Must be called before singleton instantiation.
*/
private void invokeBeanFactoryPostProcessors() throws BeansException {
String[] beanNames = getBeanDefinitionNames(BeanFactoryPostProcessor.class);
BeanFactoryPostProcessor[] factoryProcessors = new BeanFactoryPostProcessor[beanNames.length];
for (int i = 0; i < beanNames.length; i++) {
factoryProcessors[i] = (BeanFactoryPostProcessor) getBean(beanNames[i]);
}
Arrays.sort(factoryProcessors, new OrderComparator());
for (int i = 0; i < factoryProcessors.length; i++) {
BeanFactoryPostProcessor factoryProcessor = factoryProcessors[i];
factoryProcessor.postProcessBeanFactory(getBeanFactory());
}
}
/**
* Instantiate and invoke all registered BeanPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before any instantiation of application beans.
*/
private void registerBeanPostProcessors() throws BeansException {
String[] beanNames = getBeanDefinitionNames(BeanPostProcessor.class);
if (beanNames.length > 0) {
List beanProcessors = new ArrayList();
for (int i = 0; i < beanNames.length; i++) {
beanProcessors.add(getBean(beanNames[i]));
}
Collections.sort(beanProcessors, new OrderComparator());
for (Iterator it = beanProcessors.iterator(); it.hasNext();) {
getBeanFactory().addBeanPostProcessor((BeanPostProcessor) it.next());
}
}
}
/**
* Initialize the MessageSource.
* Use parent's if none defined in this context.
*/
private void initMessageSource() throws BeansException {
try {
this.messageSource = (MessageSource) getBean(MESSAGE_SOURCE_BEAN_NAME);
// Set parent message source if applicable,
// and if the message source is defined in this context, not in a parent.
if (this.parent != null && (this.messageSource instanceof HierarchicalMessageSource) &&
containsBeanDefinition(MESSAGE_SOURCE_BEAN_NAME)) {
((HierarchicalMessageSource) this.messageSource).setParentMessageSource(
getInternalParentMessageSource());
}
}
catch (NoSuchBeanDefinitionException ex) {
logger.info("No MessageSource found for context [" + getDisplayName() + "]: using empty default");
// use empty message source to be able to accept getMessage calls
this.messageSource = new StaticMessageSource();
}
}
/**
* Initialize the ApplicationEventMulticaster.
* Use SimpleApplicationEventMulticaster if none defined in the context.
* @see org.springframework.context.event.SimpleApplicationEventMulticaster
*/
private void initApplicationEventMulticaster() throws BeansException {
try {
this.applicationEventMulticaster =
(ApplicationEventMulticaster) getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME);
}
catch (NoSuchBeanDefinitionException ex) {
logger.info("No ApplicationEventMulticaster found for context [" + getDisplayName() + "]: using default");
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster();
}
}
/**
* Template method which can be overridden to add context-specific refresh work.
* Called on initialization of special beans, before instantiation of singletons.
* @throws BeansException in case of errors during refresh
* @see #refresh
*/
protected void onRefresh() throws BeansException {
// for subclasses: do nothing by default
}
/**
* Add beans that implement ApplicationListener as listeners.
* Doesn't affect other listeners, which can be added without being beans.
*/
private void refreshListeners() throws BeansException {
logger.info("Refreshing listeners");
Collection listeners = getBeansOfType(ApplicationListener.class, true, false).values();
logger.debug("Found " + listeners.size() + " listeners in bean factory");
for (Iterator it = listeners.iterator(); it.hasNext();) {
ApplicationListener listener = (ApplicationListener) it.next();
addListener(listener);
if (logger.isInfoEnabled()) {
logger.info("Application listener [" + listener + "] added");
}
}
}
/**
* Subclasses can invoke this method to register a listener.
* Any beans in the context that are listeners are automatically added.
* @param listener the listener to register
*/
protected void addListener(ApplicationListener listener) {
this.applicationEventMulticaster.addApplicationListener(listener);
}
/**
* Destroy the singletons in the bean factory of this application context.
*/
public void close() {
logger.info("Closing application context [" + getDisplayName() + "]");
// Destroy all cached singletons in this context,
// invoking DisposableBean.destroy and/or "destroy-method".
getBeanFactory().destroySingletons();
// publish corresponding event
publishEvent(new ContextClosedEvent(this));
}
//---------------------------------------------------------------------
// Implementation of BeanFactory
//---------------------------------------------------------------------
public Object getBean(String name) throws BeansException {
return getBeanFactory().getBean(name);
}
public Object getBean(String name, Class requiredType) throws BeansException {
return getBeanFactory().getBean(name, requiredType);
}
public boolean containsBean(String name) {
return getBeanFactory().containsBean(name);
}
public boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return getBeanFactory().isSingleton(name);
}
public String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return getBeanFactory().getAliases(name);
}
//---------------------------------------------------------------------
// Implementation of ListableBeanFactory
//---------------------------------------------------------------------
public int getBeanDefinitionCount() {
return getBeanFactory().getBeanDefinitionCount();
}
public String[] getBeanDefinitionNames() {
return getBeanFactory().getBeanDefinitionNames();
}
public String[] getBeanDefinitionNames(Class type) {
return getBeanFactory().getBeanDefinitionNames(type);
}
public boolean containsBeanDefinition(String name) {
return getBeanFactory().containsBeanDefinition(name);
}
public Map getBeansOfType(Class type, boolean includePrototypes, boolean includeFactoryBeans)
throws BeansException {
return getBeanFactory().getBeansOfType(type, includePrototypes, includeFactoryBeans);
}
//---------------------------------------------------------------------
// Implementation of HierarchicalBeanFactory
//---------------------------------------------------------------------
public BeanFactory getParentBeanFactory() {
return getParent();
}
/**
* Return the internal bean factory of the parent context if it implements
* ConfigurableApplicationContext; else, return the parent context itself.
* @see org.springframework.context.ConfigurableApplicationContext#getBeanFactory
*/
protected BeanFactory getInternalParentBeanFactory() {
return (getParent() instanceof ConfigurableApplicationContext) ?
((ConfigurableApplicationContext) getParent()).getBeanFactory() : (BeanFactory) getParent();
}
//---------------------------------------------------------------------
// Implementation of MessageSource
//---------------------------------------------------------------------
public String getMessage(String code, Object args[], String defaultMessage, Locale locale) {
return this.messageSource.getMessage(code, args, defaultMessage, locale);
}
public String getMessage(String code, Object args[], Locale locale) throws NoSuchMessageException {
return this.messageSource.getMessage(code, args, locale);
}
public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException {
return this.messageSource.getMessage(resolvable, locale);
}
/**
* Return the internal message source of the parent context if it is an
* AbstractApplicationContext too; else, return the parent context itself.
*/
protected MessageSource getInternalParentMessageSource() {
return (getParent() instanceof AbstractApplicationContext) ?
((AbstractApplicationContext) getParent()).messageSource : getParent();
}
//---------------------------------------------------------------------
// Abstract methods that must be implemented by subclasses
//---------------------------------------------------------------------
/**
* Subclasses must implement this method to perform the actual configuration load.
* The method is invoked by refresh before any other initialization work.
* @see #refresh
*/
protected abstract void refreshBeanFactory() throws BeansException;
/**
* 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.
* @return this application context's internal bean factory
*/
public abstract ConfigurableListableBeanFactory getBeanFactory();
/**
* Return information about this context.
*/
public String toString() {
StringBuffer sb = new StringBuffer(getClass().getName());
sb.append(": ");
sb.append("displayName=[").append(this.displayName).append("]; ");
sb.append("startup date=[").append(new Date(this.startupTime)).append("]; ");
if (this.parent == null) {
sb.append("root of ApplicationContext hierarchy");
}
else {
sb.append("parent=[").append(this.parent).append(']');
}
return sb.toString();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -