Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of javax.enterprise.inject.Instance in Spring Boot for dynamic injection

I'm migrating code from JEE to SpringBoot. I was using cool dynamic injection in JEE with javax.enterprise.inject.Instance class:

Just annotating:

@Inject
private Instance<CCIntentHandler> allMycandidates;

Will make allMycandidates be filled with all classes inheriting CCIntentHandler interface in my classpath which then I can iterate simply with:

Iterator<CCIntentHandler> iterator = allMycandidates.iterator()

Nothing more needed. How can I achieve this in Spring Boot?

Thanks

like image 585
icordoba Avatar asked Oct 18 '25 19:10

icordoba


1 Answers

Spring will inject all instances of Foo if you @Autowire a List<Foo>.

So, the Spring equivalent of ...

@Inject
private Instance<CCIntentHandler> allMycandidates;

... is:

@Autowire
private List<CCIntentHandler> allMycandidates;

Update 1 in response to this comment:

Do CCIntentHandler interface or classes implementing this interface need any Spring annotations?

Spring must be aware of any instances of CCIntentHandler, this could achieved as follows:

  • Annotate each class implementing CCIntentHandler with @Component and ensure that these classes are scanned by Spring Boot

Or

  • Provide a public method to return each class implementing CCIntentHandler and annotate each of these public methods with @Bean and ensure that the class which contains these public methods is annotated with @Configuration and that this configuration class is scanned by Spring Boot.

More details on bean declaration and dependency injection in the docs.

like image 180
glytching Avatar answered Oct 20 '25 09:10

glytching



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!