0

I am looking for a a way to do runtime injection of a bean in Quarkus. I realize this might be a bit on an unorthodox approach for quarkus, and something on an anti-pattern, so no need to point that out, I am fully aware :)

What I am looking for is a way to construct a bean during runtime, and having any annotated properties injected from the Quarkus context.

In Spring Boot I would get the application context by having a bean initialized normally by spring boot, using the ApplicationContextAware interface to inject the application context. I would then use that as a factory by calling ApplicationContext.getAutowireCapableBeanFactory() to get the auto-wire factory and using the autowireBean method on the factory to autowire my beans during runtime. I am wondering if something similar is possible in Quarkus?

Arun Sai Mustyala
  • 1,736
  • 1
  • 11
  • 27
Martin Nielsen
  • 1,865
  • 6
  • 30
  • 54
  • If you want to programmatically lookup an existing bean, there are several options (`CDI.current()` or `Arc.container()` are a good start). If you want to inject dependencies to arbitrary objects that are not CDI beans, then that's not possible. – Ladicek Oct 11 '21 at 15:09

1 Answers1

1

This is similar to this question. How to programmatically inject a Java CDI managed bean into a local variable in a (static) method

javax.enterprise.inject.spi.CDI.current().getBeanManager().select(C.class).get()

To make sure that the bean class is manged use the io.quarkus.arc.Unremovable annotation.

JDOaktown
  • 4,262
  • 7
  • 37
  • 52
donvogel
  • 76
  • 6
  • Does this mean the entire context is statically available for Quarkus? That seems almost too good to be true :). Are there any drawbacks to this method? Anything that won't get injected or behave like a "Normal" bean? I might just be a tad paranoid from working with spring. – Martin Nielsen Oct 11 '21 at 16:25
  • As long as I see, there is only the drawback with some code comventions. The bean has to be marked as managed bean. And as long as it is not used anywhere else you have to annotate it with `@Unremovable`. – donvogel Oct 12 '21 at 05:22
  • I just noticed that this creates a new bean. What i need is injection into an already created bean. Is that possible? – Martin Nielsen Oct 12 '21 at 12:25
  • I think I got your point. You want to create a instance of a bean e.g. with `new` and manualy perform injection of managed beans. I also steped over this, as `BeanManager.createInjectionTarget` is not supported in quarkus. Therfore you have to use the above method. New beans are not nessesary created. This depends on your specified scope. – donvogel Oct 12 '21 at 15:06
  • Ok thank you. I will try to modify the other parts to accept an existing bean instead. It should be possible. – Martin Nielsen Oct 13 '21 at 11:49