BeanFactory
本文最后更新于:2022年6月6日 下午
Introduction
BeanFactory interface provides a simple, yet flexible configuration mechanism to manage objects of any nature via the Spring IoC container.
The BeanFactory Interface
It’s interesting to start by having a look at the interface definition in org.springframework.beans.factory package and discuss some of its important APIs here.
The getBean() APIs
Various versions of getBean() method return an instance of the specified bean, which may be shared or independent across the application.
The containsBean() API
This method confirms if this bean factory contains a bean with the given name. More specifically, it confirms if the getBean(java.lang.String) able to obtain a bean instance with the given name.
The isSingleton() API
The isSingleton API can be used to query if this bean is a shared singleton. That is if getBean(java.lang.String) will always return the same instance.
The isPrototype() API
This API will confirm if getBean(java.lang.String) returns independent instances – meaning a bean configured with the prototype scope, or not.
The important thing to note is this method returning false does not clearly indicate a singleton object. It indicates non-independent instances, which may correspond to other scopes as well.
We need to use the isSingleton(java.lang.String) operation to explicitly check for a shared singleton instance.
Other APIs
While the isTypeMatch(String name, Class targetType) method checks whether the bean with the given name matches the specified type, getType(String name) is useful in identifying the type of the bean with the given name.
Finally, getAliases(String name) return the aliases for the given bean name, if any.
BeanFactory API
BeanFactory holds bean definitions and instantiates them whenever asked for by the client application – which means:
- It takes care of the lifecycle of a bean by instantiating it and calling appropriate destruction methods
- It is capable of creating associations between dependent object while instantiating them
- It is important to point that BeanFactory does not support the Annotation-based dependency Injection whereas ApplicationContext, a superset of BeanFactory does
Do have a read on Application Context to find out what it can do extra.
Defining the Bean
1 |
|
Configuring the BeanFactory with XML
1 |
|
BeanFactory with ClassPathResource
1 |
|