Beans

Learn about a few interview questions regarding beans.

What are beans in Spring?

Simply put, a Spring bean is a Java object. When Java objects are created by the Spring container, they are referred to as Spring Beans.

Beans are managed by the Spring container using the configuration metadata in the form of XML or Java annotations. The container instantiates, assembles and manages the lifecycle of a bean. For example, the @Component annotation on a class tells Spring framework that it has to manage the lifecycle of the objects of that class.

What is the lifecycle of a Spring Bean?

Spring container instantiates a bean and initializes it. It also injects the required dependencies. When the context is destroyed, all the initialized beans are also destroyed.

Spring provides post initialization and pre destruction methods for custom tasks. These methods can be invoked using XML config file or Java annotations.

What are custom bean lifecycle methods?

During the lifecycle of the bean, Spring allows the developer to add custom code during bean initialization and bean destruction. This can include code for custom business logic at initialization or destruction as well as setting up and cleaning up resources like a database connection or a file etc.

The XML tags init-method and destroy-method are used to define the custom methods inside the <bean> tag. The @PostContruct and @PreDestroy annotations also accomplish the same task.

What are some features of custom init and destroy methods?

  • Custom methods for initialization and destruction can have any name.
  • They can have any access modifier; private, public, or protected.
  • They can have any return type, but since the return value cannot be captured, void is mostly used as the return type.
  • They cannot have any input arguments.

What information does the bean definition contain?

Bean definition contains information for the container in the form of configuration metadata. Bean’s definition contains the following information:

  • How the bean is created.
  • Lifecycle details of the bean.
...