Registering beans(prototype) at runtime in Spring

This is purely my opinion, not an expert view:

Spring provides two mechanisms for custom modification of an application context – using BeanFactoryPostProcessor which allows for modification of existing bean definitions or adding new bean definitions, and BeanPostProcessors which allows for modification of bean instances(wrapping them around proxy etc).

Spring does not provide any other native way to dynamically add bean definitions or bean instances at runtime, but like you have done by getting hold of the underlying bean factory instances and adding in bean definitions is one way to go. It works, but there are risks:

  • What happens if you overwrite an existing bean name with a new type, how are places where this bean is already injected handled. Also, what happens if a existing bean name is overwritten with a totally different type!

  • This newly registered bean will not have any fields autowired in, and will not be injected into other beans also – so essentially the bean factory is purely acting as a registry for holding the bean, not really a dependency injection functionality!

  • if a refresh() is called on the application context then the backing bean factory will be overwritten and a new one created, thus any bean instances registered against the bean factory directly will be lost.

If the objective is purely to create beans which has been autowired by Spring, I would go for something like @Configurable. If the risks above are acceptable also your approach should work.

Leave a Comment