2

In my Spring project I use extensively collections from vavr library. Sometimes I need to inject collection of beans. As far as I know Spring can only inject collections from JDK, e.g. List, Set, Map, etc. Is there any way to inject vavr collection? I would like to do something like this:

@Component
class NameResolver {

    @Autowired
    io.vavr.collection.List<NameMatcher> matchers; // how to make it work?
}
k13i
  • 4,011
  • 3
  • 35
  • 63
  • yes you can autowired this Collection. but it should be in maven dependencies list. – Lova Chittumuri Jun 13 '19 at 11:38
  • What excatly? I have vavr library on the classpath. – k13i Jun 13 '19 at 11:40
  • Then you can place your jar in Nexus repository there by you can add in maven – Lova Chittumuri Jun 13 '19 at 11:45
  • I do have this dependency. I fetch it from Maven Central https://mvnrepository.com/artifact/io.vavr/vavr/0.10.0 – k13i Jun 13 '19 at 11:52
  • As long as there is a list of that type as a bean available Spring will inject it. It will not inject the beans of that type automatically it will only do that for JDK collections. One workaround is to inject the normal collection and when needed wrap it in the vavr one. – M. Deinum Jun 13 '19 at 11:54
  • That's the way I do this currently (i.e. inject JDK collection and then wrap it in vavr collection) but I was thinking there is a way to avoid this additional step – k13i Jun 13 '19 at 12:04

1 Answers1

4

You are correct that Spring only supports injecting JDK collections of spring beans. You can work around this with a kind of a bridge @Bean factory method in one of your @Configuration classes, similar to this:

import io.vavr.collection.List;
import java.util.Collection;

...

@Bean
public List<NameMatcher> vavrMatchers(Collection<NameMatcher> matchers) {
    return List.ofAll(matchers);
}

With the above, you created a vavr List that is also a Spring bean, so you can @Autowire it into other Spring beans. It saves you from wrapping at the injection site, so you only have to do it once for each collection of beans, instead of once for each @Autowired injection site.

Nándor Előd Fekete
  • 6,988
  • 1
  • 22
  • 47