Sobes.tech
Middle+

What is BeanDefinition and what is it used for?

sobes.tech AI

Answer from AI

BeanDefinition is an abstraction of metadata describing a bean in the Spring container. It defines the bean configuration:

  • Bean class (beanClass)
  • Initialization and destruction behavior (initMethod, destroyMethod)
  • Scope (scope)
  • Dependencies on other beans (propertyValues, constructorArgumentValues)
  • Lazy initialization (lazyInit)
  • Priority (primary)
  • Factory method or bean (factoryBeanName, factoryMethodName)

It is used for:

  1. Registering beans: The container uses BeanDefinition to register beans in its registry before the bean itself is created.
  2. Configuring beans: BeanDefinition contains all the information needed by the container to create and configure a bean instance.
  3. Deferred creation: The container can read BeanDefinition and delay the creation of the bean instance until its first request.
  4. Programmatic management: BeanDefinition allows programmatic creation and modification of bean configurations, for example, when using XML files or configuration classes in Java.

Example of creating a BeanDefinition programmatically:

// org.springframework.beans.factory.config.BeanDefinition
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(MyService.class); // Set class
beanDefinition.setScope("singleton");        // Set scope
beanDefinition.setLazyInit(true);           // Set lazy initialization

// Adding a property
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("dependency", new RuntimeBeanReference("myDependencyBean"));
beanDefinition.setPropertyValues(propertyValues);

// Constructor with argument
ConstructorArgumentValues constructorArguments = new ConstructorArgumentValues();
constructorArguments.addGenericArgumentValue("initialValue");
beanDefinition.setConstructorArgumentValues(constructorArguments);

// Register in BeanFactory
// DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
// beanFactory.registerBeanDefinition("myService", beanDefinition);

Main implementations of BeanDefinition:

  • RootBeanDefinition: Represents the final, consolidated bean configuration.
  • ChildBeanDefinition: Represents a bean configuration that inherits from another bean.
  • GenericBeanDefinition: A universal implementation that can be used to create beans of any complexity.