Search code examples
javaspringejbcdi

Does Spring Context have equivalent of Java CDI's @Inject @Any


In Java CDI there is great functionality on gathering all managed beans, that share a supertype. Let's say I what to gather all managed instances of MyInterceptor, I just have to write:

@Inject
@Any
Instance<MyInterceptor> myInterceptors;

Similar functionality I was able to obtain when I was working on EJB, although solution there was way less pretty (I needed to call BeanManager).

Can similar functionality I can obtain working on @Component's managed by Spring context?

[Edit] Why is not a duplicate of What is the Spring equivalent for CDI's Instance, or Guices Provider
From my understanding, in the above question, there is a hidden assumption, that I have both contexts: Spring and CDI, which may not be always the case (especially in Java SE applications). Furthermore, I have a bad experience in mixing contexts, they often claim that they are compatible, but it isn't always the case. You can get trapped in unexpected problems, like this: https://blog.akquinet.de/2017/01/04/dont-get-trapped-into-a-memory-leak-using-cdi-instance-injection/


Solution

  • If you specify the the field as a List with a generic type MyInterctptor you should be able to achieve what you are looking for. Ex:

    @Autowired
    List<MyInterceptor> interceptors;
    

    More info can be found here: https://dzone.com/articles/load-all-implementors