Search code examples
spring-bootkotlinamqpspring-amqp

Create beans on application load


Before starting to read, that's a list of the links I've tried to read to solve this issue:

  1. Spring : Create beans at runtime
  2. How to add bean instance at runtime in spring WebApplicationContext?
  3. https://www.logicbig.com/tutorials/spring-framework/spring-core/bean-definition.html
  4. Spring - Programmatically generate a set of beans
  5. How do I create beans programmatically in Spring Boot?

I'm using SpringBoot and RabbitMQ for my services and lately, I've read this article: https://programmerfriend.com/rabbit-mq-retry/

I would like to generalize this idea and create a SpringBoot library that can get in the names of the queues that need to be created via the application.properties file and do everything behind the scenes, so the creation of the different queues and the binding between them will happen "automagically" whenever I'll integrate the library into a service.

The problem which I'm facing is basically to have the same behavior @Bean gives me. I need to repeat this behavior multiple N times (as many as the number of names specified in my application.properties).

From what I could see online, there's a possibility to create beans when the app is loaded, but the only way to do it is by telling the context what type of class you want to generate and let Spring handle it itself. as the class I want to generate does not contain a default constructor (and does not controlled by me), I wondered if there's a way to create an object and add this specific instance to the application context.


Solution

  • but the only way to do it is by telling the context what type of class you want to generate and let Spring handle it itself

    No; since 5.0 you can now provide a Supplier for the bean.

    /**
     * Register a bean from the given bean class, using the given supplier for
     * obtaining a new instance (typically declared as a lambda expression or
     * method reference), optionally customizing its bean definition metadata
     * (again typically declared as a lambda expression).
     * <p>This method can be overridden to adapt the registration mechanism for
     * all {@code registerBean} methods (since they all delegate to this one).
     * @param beanName the name of the bean (may be {@code null})
     * @param beanClass the class of the bean
     * @param supplier a callback for creating an instance of the bean (in case
     * of {@code null}, resolving a public constructor to be autowired instead)
     * @param customizers one or more callbacks for customizing the factory's
     * {@link BeanDefinition}, e.g. setting a lazy-init or primary flag
     * @since 5.0
     */
    public <T> void registerBean(@Nullable String beanName, Class<T> beanClass,
            @Nullable Supplier<T> supplier, BeanDefinitionCustomizer... customizers) {
    

    So

    context.registerBean("fooBean", Foo.class, () -> someInstance);