Can dependencies be injected into a native script plugin?


I have a script factory class that has some dependencies that I usually manage with a Spring context. I understand ElasticSearch uses Guice internally, so I sorta naively thought things might just work if I use the javax.inject annotations.

This is what I tried:

public static class Factory implements NativeScriptFactory {
  private Foo foo;
  private Bar bar;

  public Factory() {}

  public ExecutableScript newScript(Map<String, Object> params) {
    // use foo and bar to create the script

As you might expect, I get NullPointerExceptions when I perform a function_score query using this particular script. Is there any way to accomplish what I'm trying to do here?

(Nik Everett) #2

Use constructor injection and it should work. You might have to use a
different @Inject. I don't remember the package. I wouldn't be surprised if
the javax one works though.


Yep, constructor injection ended up working! javax.inject didn't work for me, but the elasticsearch version did. Unfortunately I realized that I had some beans that had @Value-annotated arguments derived from system properties, so it wasn't straightforward to get those working with Guice. For now I've resorted to creating a SpringContextModule class that extends elasticsearch's AbstractModule and contains a @Provides method for the spring context.

(Nik Everett) #4

That sounds like what I'd try, yes.

(system) #5