Spring Bean basic concepts simplified


- Java Beginners
Spring IoC container can manage more than one bean. Beans are created with details provided via metadata configuration to container (via Java code, Java Annotation, XML). Bean Definitions are represented as the Object of BeanDefinition that contains the several metadata information.
Properties those are part of BeanDefinitions are
  1. Class
  2. Name
  3. Scope
  4. Constructor Argument
  5. Properties
  6. Autowiring mode
  7. lazy-initializinng-mode
  8. Initialization method
  9. Destruction method

Registering Beans created outside Container

In order to register beans created outside container by user, we can use BeanFactory(DefaultListableBeanFactory) (Accessed by getBeanFactory() method). Accessed beanfactory can be used to register the existing bean via registerSingleton() & registerBeanDefinition() methods.

Bean Naming Convention

Every bean in a single container can have one or more then one(treated as Alias) identifier(referenced via id / Name) but these identifier needs to be unique. Id / Name are not required attributes so user is not forced to provide Id / Name for a given bean. In case user does not provide any(Id / Name) of them container will generate unique name for the same. Aliases can be create by providing different option in name attributes these options should be separated by comma.

Bean Instantiation

Container combine the application class and metadata configuration details to build the beans. There are different ways a container can build the Beans.
  1. Constructor Instantiation
  2. Static Factory Method Instantiation
  3. Instance Factory Method Instantiation

Constructor Instantiation

For Constructor instantiation bean class(class attribute in <bean>) is required. Default constructor of class may also be required.

Example of constructor instantiation with XML based metadata.

<bean id="HibernateDao"  class="com.dao.HibernateDaoImpl">
</bean>
 

Static Factory Method Instatiation

In this case bean will be created by calling static factory method of a Class. Spring container doesn't have direct involvement in defining the beans.

Example of Static Factory instantiation with XML based metadata.

<bean id="contactService"
class="com.ContactService"
factory-method="createInstance"/>
Here we are defining class having static factory method(createInstance).
You know, the comment floor is all yours. I would appreciate, if you make use of it.