Skip to content

CustomInjectionPoints

Ruedi Steinmann edited this page Mar 27, 2015 · 2 revisions

support for injection points with other annotations _

Custom Injection Points

In addition to the standard @Inject-driven injections, Salta includes hooks for custom injection points. This enables Salta to host other frameworks that have their own injection semantics or annotations. Most developers won't use custom injections directly; but they may see their use in extensions and third-party libraries.

In salta, a RecipeMembersInjector is responsible for identifying injection points (typically fields or methods) which need to be set or invoked during instance creation.

For example, let's provide for the standard @javax.annotation.Resource annotation:

@Override
protected void configure() throws Exception {
  // save the config for later use. May not use any function of
  // the Binder or AbstractModule after configure() returned
  CoreInjectorConfiguration config = config().standardConfig.config;

  bindMembersInjectorFactory(new RecipeMembersInjectorFactory() {
    @Override
    public List<RecipeMembersInjector> createMembersInjectors(
        RecipeCreationContext ctx, TypeToken<?> type) {
      ArrayList<RecipeMembersInjector> result = new ArrayList<>();
      // iterate all ancestors
      for (TypeToken<?> currentType : type.getTypes()) {

        // iterate the fields
        for (Field field : currentType.getRawType()
            .getDeclaredFields()) {

          // try to get the resource annotation
          Resource resource = field
              .getAnnotation(Resource.class);
          if (resource != null) {
            // if the annotation is present,
            // register an injector
            TypeToken<?> fieldType = currentType
                .resolveType(field.getGenericType());
            result.add(new FixedFieldRecipeMembersInjector(
                field,
                new SupplierRecipeImpl(
                    () -> retrieveResource(
                        fieldType, resource)),
                        config.injectionStrategy));
          }
        }
      }
      return result;
    }

  });
}

To extend this example to method injection, use a FixedMethodInjector. To handle method overrides, there is a MethodOverrideIndex, which tells you if a method is overridden or not (typically, you only inject into non-overridden methods).

Clone this wiki locally