简体   繁体   中英

Guice Constructor Parameter Custom Annotation Injection

Is there a way to implement, in Guice , injection for a constructor parameter annotated with a custom annotation?

My question is almost exactly the same as this one: Guice Custom Injection for constructor parameters

However, that was about 5 years ago. I would be interested to see if anything has changed.

I need to resolve parameters based on some qualifier like a name but those names must be resolved at runtime (ie I can't just compile in the @Named annotation).

A contrived example:

public class MyService
{
  private final DataStore store;

  @Inject
  public MyService(@DataStoreType("sqlite") final DataStore store)
  {
    this.store = store;
  }
  ...
}

And some kind of resolve something or another dynamic resolver like this:

public DataStore resolve(final DataStoreType annotation)
{
  if ("sqlite".equals(annotation.value())
  {
    return sqliteStore;
  }
  else if ("postgresql".equals(annotation.value())
  {
    return pgStore;
  }
  ...
}

For those familiar with HK2 / Jersey I'm looking for something like org.glassfish.hk2.api.InjectionResolver in Guice

This case may be solved using a Factory . Just move the logic from resolve() method to Factory.create(DataStoreType) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM