dynamically declare beans at runtime in Spring

The common way to have different beans in the application context is using profiles. You can read about profiles in the following spring source posts:

About your first question, you can declare beans at runtime via BeanDefinitionRegistry.registerBeanDefinition() method, for example:

  BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(SomeClass.class);
  builder.addPropertyReference("propertyName", "someBean");  // add dependency to other bean
  builder.addPropertyValue("propertyName", someValue);      // set property value
  DefaultListableBeanFactory factory = (DefaultListableBeanFactory) context.getBeanFactory();
  factory.registerBeanDefinition("beanName", builder.getBeanDefinition());

Is possible also to register a singleton bean instance (already configured) with

context.getBeanFactory().registerSingleton(beanName, singletonObject)

Finally, Spring don’t provides a clear way to change a bean after refreshing the context, but the most common approachs are:

Leave a Comment