google / guice

Guice (pronounced 'juice') is a lightweight dependency injection framework for Java 11 and above, brought to you by Google.
https://github.com/google/guice
Apache License 2.0
12.51k stars 1.67k forks source link

Feature Request : Ability to specify additional annotation as injecetion points #1813

Open GedMarc opened 6 months ago

GedMarc commented 6 months ago

Hi Guys,

A few of the newer libraries are mixing and matching other annotations for injection points, such as MicroProfile Config, Whereby the @ConfigProperty(name = "test") is both a named, and an injection point.

I have overcome this through shading the guice-core library, and adding a very simple SPI Interface to InjectionPoint class,

static Annotation getAtInject(AnnotatedElement member) {
    Annotation a = member.getAnnotation(jakarta.inject.Inject.class);
    a = a == null ? member.getAnnotation(Inject.class) : a;
    //#GedMarc update to allow alternative injection pointers
    if(a == null) {
      List<Class<? extends Annotation>> annotations = new ArrayList<>();
      ServiceLoader<InjectionPointProvider> load = ServiceLoader.load(InjectionPointProvider.class);
      load.forEach(iPoint -> {
        annotations.add(iPoint.injectionPoint(member));
      });
      for (Class<? extends Annotation> annotation : annotations) {
          //noinspection ConstantValue
          if (a == null) {
         a= member.getAnnotation(annotation);
          if (a != null) {
            a = new Inject(){
              @Override
              public Class<? extends Annotation> annotationType() {
                return annotation;
              }
              @Override
              public boolean optional() {
                return member.isAnnotationPresent(Nullable.class);
              }
            };
            break;
          }
        }
      }
    }
    return a;
  }

While I am sure there is probably a much cleaner way to implement this functionality, this rather simple extension works perfectly so far across the spectrum (of my visibility)

Would it be possible to consider such an update to the Guice framework for enabling this modification of Injectables, to allow any custom annotation binding to be used as an injection point according to a client service provider?

This has been done in the GuicedEE framework, to enable MicroProfile and meet the TCK requirements,

Many thanks

GedMarc commented 6 months ago

As we know PR's get resolved internally, I apologize for the white spaces, if it needs to be updated please let me know (y)