public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry
DefaultListableBeanFactory
instance and does not assume a specific bean definition format. Implements
the BeanDefinitionRegistry
interface in order to allow for applying any bean definition readers to it.
Typical usage is to register a variety of bean definitions via the
BeanDefinitionRegistry
interface and then call AbstractApplicationContext.refresh()
to initialize those beans
with application context semantics (handling
ApplicationContextAware
, auto-detecting
BeanFactoryPostProcessors
,
etc).
In contrast to other ApplicationContext implementations that create a new
internal BeanFactory instance for each refresh, the internal BeanFactory of
this context is available right from the start, to be able to register bean
definitions on it. AbstractApplicationContext.refresh()
may only be called once.
Usage example:
GenericApplicationContext ctx = new GenericApplicationContext(); XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx); xmlReader.loadBeanDefinitions(new ClassPathResource("applicationContext.xml")); PropertiesBeanDefinitionReader propReader = new PropertiesBeanDefinitionReader(ctx); propReader.loadBeanDefinitions(new ClassPathResource("otherBeans.properties")); ctx.refresh(); MyBean myBean = (MyBean) ctx.getBean("myBean"); ...For the typical case of XML bean definitions, simply use
ClassPathXmlApplicationContext
or FileSystemXmlApplicationContext
,
which are easier to set up - but less flexible, since you can just use standard
resource locations for XML bean definitions, rather than mixing arbitrary bean
definition formats. The equivalent in a web environment is
XmlWebApplicationContext
.
For custom application context implementations that are supposed to read
special bean definition formats in a refreshable manner, consider deriving
from the AbstractRefreshableApplicationContext
base class.
registerBeanDefinition(java.lang.String, org.springframework.beans.factory.config.BeanDefinition)
,
AbstractApplicationContext.refresh()
,
XmlBeanDefinitionReader
,
PropertiesBeanDefinitionReader
DefaultResourceLoader.ClassPathContextResource
APPLICATION_EVENT_MULTICASTER_BEAN_NAME, LIFECYCLE_PROCESSOR_BEAN_NAME, logger, MESSAGE_SOURCE_BEAN_NAME
CONFIG_LOCATION_DELIMITERS, CONVERSION_SERVICE_BEAN_NAME, ENVIRONMENT_BEAN_NAME, LOAD_TIME_WEAVER_BEAN_NAME, SYSTEM_ENVIRONMENT_BEAN_NAME, SYSTEM_PROPERTIES_BEAN_NAME
FACTORY_BEAN_PREFIX
CLASSPATH_ALL_URL_PREFIX
CLASSPATH_URL_PREFIX
Constructor and Description |
---|
GenericApplicationContext()
Create a new GenericApplicationContext.
|
GenericApplicationContext(ApplicationContext parent)
Create a new GenericApplicationContext with the given parent.
|
GenericApplicationContext(DefaultListableBeanFactory beanFactory)
Create a new GenericApplicationContext with the given DefaultListableBeanFactory.
|
GenericApplicationContext(DefaultListableBeanFactory beanFactory,
ApplicationContext parent)
Create a new GenericApplicationContext with the given DefaultListableBeanFactory.
|
Modifier and Type | Method and Description |
---|---|
protected void |
cancelRefresh(BeansException ex)
Cancel this context's refresh attempt, resetting the
active flag
after an exception got thrown. |
protected void |
closeBeanFactory()
Not much to do: We hold a single internal BeanFactory that will never
get released.
|
AutowireCapableBeanFactory |
getAutowireCapableBeanFactory()
Return this context's internal bean factory as AutowireCapableBeanFactory,
if already available.
|
BeanDefinition |
getBeanDefinition(String beanName)
Return the BeanDefinition for the given bean name.
|
ConfigurableListableBeanFactory |
getBeanFactory()
Return the single internal BeanFactory held by this context
(as ConfigurableListableBeanFactory).
|
ClassLoader |
getClassLoader()
Return the ClassLoader to load class path resources with.
|
DefaultListableBeanFactory |
getDefaultListableBeanFactory()
Return the underlying bean factory of this context,
available for registering bean definitions.
|
Resource |
getResource(String location)
This implementation delegates to this context's ResourceLoader if set,
falling back to the default superclass behavior else.
|
Resource[] |
getResources(String locationPattern)
This implementation delegates to this context's ResourceLoader if it
implements the ResourcePatternResolver interface, falling back to the
default superclass behavior else.
|
boolean |
isAlias(String beanName)
Determine whether this given name is defines as an alias
(as opposed to the name of an actually registered component).
|
boolean |
isBeanNameInUse(String beanName)
Determine whether the given bean name is already in use within this registry,
i.e.
|
protected void |
refreshBeanFactory()
Do nothing: We hold a single internal BeanFactory and rely on callers
to register beans through our public methods (or the BeanFactory's).
|
void |
registerAlias(String beanName,
String alias)
Given a name, register an alias for it.
|
<T> void |
registerBean(Class<T> beanClass,
BeanDefinitionCustomizer... customizers)
Register a bean from the given bean class, optionally customizing its
bean definition metadata (typically declared as a lambda expression).
|
<T> void |
registerBean(Class<T> beanClass,
Supplier<T> supplier,
BeanDefinitionCustomizer... customizers)
Register a bean from the given bean class, using the given supplier for
obtaining a new instance (typically declared as a lambda expression or
method reference), optionally customizing its bean definition metadata
(again typically declared as a lambda expression).
|
<T> void |
registerBean(String beanName,
Class<T> beanClass,
BeanDefinitionCustomizer... customizers)
Register a bean from the given bean class, optionally customizing its
bean definition metadata (typically declared as a lambda expression).
|
<T> void |
registerBean(String beanName,
Class<T> beanClass,
Supplier<T> supplier,
BeanDefinitionCustomizer... customizers)
Register a bean from the given bean class, using the given supplier for
obtaining a new instance (typically declared as a lambda expression or
method reference), optionally customizing its bean definition metadata
(again typically declared as a lambda expression).
|
void |
registerBeanDefinition(String beanName,
BeanDefinition beanDefinition)
Register a new bean definition with this registry.
|
void |
removeAlias(String alias)
Remove the specified alias from this registry.
|
void |
removeBeanDefinition(String beanName)
Remove the BeanDefinition for the given name.
|
void |
setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding)
Set whether it should be allowed to override bean definitions by registering
a different definition with the same name, automatically replacing the former.
|
void |
setAllowCircularReferences(boolean allowCircularReferences)
Set whether to allow circular references between beans - and automatically
try to resolve them.
|
void |
setClassLoader(ClassLoader classLoader)
Specify the ClassLoader to load class path resources with, or
null
for using the thread context class loader at the time of actual resource access. |
void |
setParent(ApplicationContext parent)
Set the parent of this application context, also setting
the parent of the internal BeanFactory accordingly.
|
void |
setResourceLoader(ResourceLoader resourceLoader)
Set a ResourceLoader to use for this context.
|
addApplicationListener, addBeanFactoryPostProcessor, assertBeanFactoryActive, close, containsBean, containsBeanDefinition, containsLocalBean, createEnvironment, destroy, destroyBeans, doClose, findAnnotationOnBean, finishBeanFactoryInitialization, finishRefresh, getAliases, getApplicationListeners, getApplicationName, getBean, getBean, getBean, getBean, getBean, getBeanDefinitionCount, getBeanDefinitionNames, getBeanFactoryPostProcessors, getBeanNamesForAnnotation, getBeanNamesForType, getBeanNamesForType, getBeanNamesForType, getBeanProvider, getBeanProvider, getBeansOfType, getBeansOfType, getBeansWithAnnotation, getDisplayName, getEnvironment, getId, getInternalParentBeanFactory, getInternalParentMessageSource, getMessage, getMessage, getMessage, getParent, getParentBeanFactory, getResourcePatternResolver, getStartupDate, getType, initApplicationEventMulticaster, initLifecycleProcessor, initMessageSource, initPropertySources, invokeBeanFactoryPostProcessors, isActive, isPrototype, isRunning, isSingleton, isTypeMatch, isTypeMatch, obtainFreshBeanFactory, onClose, onRefresh, postProcessBeanFactory, prepareBeanFactory, prepareRefresh, publishEvent, publishEvent, publishEvent, refresh, registerBeanPostProcessors, registerListeners, registerShutdownHook, resetCommonCaches, setDisplayName, setEnvironment, setId, start, stop, toString
addProtocolResolver, clearResourceCaches, getProtocolResolvers, getResourceByPath, getResourceCache
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
containsBeanDefinition, getBeanDefinitionCount, getBeanDefinitionNames
getAliases
addProtocolResolver
public GenericApplicationContext()
public GenericApplicationContext(DefaultListableBeanFactory beanFactory)
beanFactory
- the DefaultListableBeanFactory instance to use for this contextregisterBeanDefinition(java.lang.String, org.springframework.beans.factory.config.BeanDefinition)
,
AbstractApplicationContext.refresh()
public GenericApplicationContext(@Nullable ApplicationContext parent)
parent
- the parent application contextregisterBeanDefinition(java.lang.String, org.springframework.beans.factory.config.BeanDefinition)
,
AbstractApplicationContext.refresh()
public GenericApplicationContext(DefaultListableBeanFactory beanFactory, ApplicationContext parent)
beanFactory
- the DefaultListableBeanFactory instance to use for this contextparent
- the parent application contextregisterBeanDefinition(java.lang.String, org.springframework.beans.factory.config.BeanDefinition)
,
AbstractApplicationContext.refresh()
public void setParent(@Nullable ApplicationContext parent)
setParent
in interface ConfigurableApplicationContext
setParent
in class AbstractApplicationContext
parent
- the parent contextConfigurableBeanFactory.setParentBeanFactory(org.springframework.beans.factory.BeanFactory)
public void setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding)
DefaultListableBeanFactory.setAllowBeanDefinitionOverriding(boolean)
public void setAllowCircularReferences(boolean allowCircularReferences)
Default is "true". Turn this off to throw an exception when encountering a circular reference, disallowing them completely.
AbstractAutowireCapableBeanFactory.setAllowCircularReferences(boolean)
public void setResourceLoader(ResourceLoader resourceLoader)
getResource
calls to the given ResourceLoader.
If not set, default resource loading will apply.
The main reason to specify a custom ResourceLoader is to resolve resource paths (without URL prefix) in a specific fashion. The default behavior is to resolve such paths as class path locations. To resolve resource paths as file system locations, specify a FileSystemResourceLoader here.
You can also pass in a full ResourcePatternResolver, which will
be autodetected by the context and used for getResources
calls as well. Else, default resource pattern matching will apply.
public Resource getResource(String location)
getResource
in interface ResourceLoader
getResource
in class DefaultResourceLoader
location
- the resource locationnull
)setResourceLoader(org.springframework.core.io.ResourceLoader)
public Resource[] getResources(String locationPattern) throws IOException
getResources
in interface ResourcePatternResolver
getResources
in class AbstractApplicationContext
locationPattern
- the location pattern to resolveIOException
- in case of I/O errorssetResourceLoader(org.springframework.core.io.ResourceLoader)
public void setClassLoader(@Nullable ClassLoader classLoader)
DefaultResourceLoader
null
for using the thread context class loader at the time of actual resource access.
The default is that ClassLoader access will happen using the thread context class loader at the time of this ResourceLoader's initialization.
setClassLoader
in class DefaultResourceLoader
@Nullable public ClassLoader getClassLoader()
DefaultResourceLoader
Will get passed to ClassPathResource's constructor for all ClassPathResource objects created by this resource loader.
getClassLoader
in interface ResourceLoader
getClassLoader
in class DefaultResourceLoader
null
if even the system ClassLoader isn't accessible)ClassPathResource
protected final void refreshBeanFactory() throws IllegalStateException
refreshBeanFactory
in class AbstractApplicationContext
IllegalStateException
- if already initialized and multiple refresh
attempts are not supportedregisterBeanDefinition(java.lang.String, org.springframework.beans.factory.config.BeanDefinition)
protected void cancelRefresh(BeansException ex)
AbstractApplicationContext
active
flag
after an exception got thrown.cancelRefresh
in class AbstractApplicationContext
ex
- the exception that led to the cancellationprotected final void closeBeanFactory()
closeBeanFactory
in class AbstractApplicationContext
public final ConfigurableListableBeanFactory getBeanFactory()
getBeanFactory
in interface ConfigurableApplicationContext
getBeanFactory
in class AbstractApplicationContext
null
)AbstractApplicationContext.refreshBeanFactory()
,
AbstractApplicationContext.closeBeanFactory()
public final DefaultListableBeanFactory getDefaultListableBeanFactory()
NOTE: You need to call AbstractApplicationContext.refresh()
to initialize the
bean factory and its contained beans with application context semantics
(autodetecting BeanFactoryPostProcessors, etc).
public AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException
AbstractApplicationContext
getAutowireCapableBeanFactory
in interface ApplicationContext
getAutowireCapableBeanFactory
in class AbstractApplicationContext
IllegalStateException
- if the context does not support the
AutowireCapableBeanFactory
interface, or does not hold an
autowire-capable bean factory yet (e.g. if refresh()
has
never been called), or if the context has been closed alreadyAbstractApplicationContext.getBeanFactory()
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException
BeanDefinitionRegistry
registerBeanDefinition
in interface BeanDefinitionRegistry
beanName
- the name of the bean instance to registerbeanDefinition
- definition of the bean instance to registerBeanDefinitionStoreException
- if the BeanDefinition is invalidBeanDefinitionOverrideException
- if there is already a BeanDefinition
for the specified bean name and we are not allowed to override itGenericBeanDefinition
,
RootBeanDefinition
,
ChildBeanDefinition
public void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException
BeanDefinitionRegistry
removeBeanDefinition
in interface BeanDefinitionRegistry
beanName
- the name of the bean instance to registerNoSuchBeanDefinitionException
- if there is no such bean definitionpublic BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException
BeanDefinitionRegistry
getBeanDefinition
in interface BeanDefinitionRegistry
beanName
- name of the bean to find a definition fornull
)NoSuchBeanDefinitionException
- if there is no such bean definitionpublic boolean isBeanNameInUse(String beanName)
BeanDefinitionRegistry
isBeanNameInUse
in interface BeanDefinitionRegistry
beanName
- the name to checkpublic void registerAlias(String beanName, String alias)
AliasRegistry
registerAlias
in interface AliasRegistry
beanName
- the canonical namealias
- the alias to be registeredpublic void removeAlias(String alias)
AliasRegistry
removeAlias
in interface AliasRegistry
alias
- the alias to removepublic boolean isAlias(String beanName)
AliasRegistry
isAlias
in interface AliasRegistry
beanName
- the name to checkpublic final <T> void registerBean(Class<T> beanClass, BeanDefinitionCustomizer... customizers)
beanClass
- the class of the bean (resolving a public constructor
to be autowired, possibly simply the default constructor)customizers
- one or more callbacks for customizing the factory's
BeanDefinition
, e.g. setting a lazy-init or primary flagregisterBean(String, Class, Supplier, BeanDefinitionCustomizer...)
public final <T> void registerBean(@Nullable String beanName, Class<T> beanClass, BeanDefinitionCustomizer... customizers)
beanName
- the name of the bean (may be null
)beanClass
- the class of the bean (resolving a public constructor
to be autowired, possibly simply the default constructor)customizers
- one or more callbacks for customizing the factory's
BeanDefinition
, e.g. setting a lazy-init or primary flagregisterBean(String, Class, Supplier, BeanDefinitionCustomizer...)
public final <T> void registerBean(Class<T> beanClass, Supplier<T> supplier, BeanDefinitionCustomizer... customizers)
beanClass
- the class of the beansupplier
- a callback for creating an instance of the beancustomizers
- one or more callbacks for customizing the factory's
BeanDefinition
, e.g. setting a lazy-init or primary flagregisterBean(String, Class, Supplier, BeanDefinitionCustomizer...)
public <T> void registerBean(@Nullable String beanName, Class<T> beanClass, @Nullable Supplier<T> supplier, BeanDefinitionCustomizer... customizers)
This method can be overridden to adapt the registration mechanism for
all registerBean
methods (since they all delegate to this one).
beanName
- the name of the bean (may be null
)beanClass
- the class of the beansupplier
- a callback for creating an instance of the bean (in case
of null
, resolving a public constructor to be autowired instead)customizers
- one or more callbacks for customizing the factory's
BeanDefinition
, e.g. setting a lazy-init or primary flag