Динамическая инъекция Guice с пользовательской аннотацией

У меня есть какой-то ресурс, но я не могу итераторить его и привязывать их все, мне нужно использовать ключ для запроса ресурса. Итак, я должен динамически вводить.

Я определяю аннотацию как

@Target({ METHOD, CONSTRUCTOR, FIELD })
@Retention(RUNTIME)
@Documented
@BindingAnnotation
public @interface Res
{
    String value();// the key of the resource
}

использовать вот так

public class Test
{
    @Inject
    @Res("author.name")
    String name;
    @Inject
    @Res("author.age")
    int age;
    @Inject
    @Res("author.blog")
    Uri blog;
}

Мне нужно обработать инъекцию, аннотированную @Res, и мне нужно знать поле инъекции и аннотацию.

Возможно ли это в Guice и как? даже со спи?


person wener    schedule 12.06.2014    source источник


Ответы (1)


Я работаю над CustomInjections

Такой код

public class PropsModule extends AbstractModule
{
    private final Props props;
    private final InProps inProps;

    private PropsModule(Props props)
    {
        this.props = props;
        this.inProps = InProps.in(props);
    }

    public static PropsModule of(Props props)
    {
        return new PropsModule(props);
    }

    @Override
    protected void configure()
    {
        bindListener(Matchers.any(), new TypeListener()
        {
            @Override
            public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter)
            {
                Class<? super I> clazz = type.getRawType();
                if (!clazz.isAnnotationPresent(WithProp.class))
                    return;
                for (Field field : clazz.getDeclaredFields())
                {
                    Prop prop = field.getAnnotation(Prop.class);
                    if (prop == null)
                        continue;

                    encounter.register(new PropInjector<I>(prop, field));
                }
            }
        });
    }

    class PropInjector<T> implements MembersInjector<T>
    {
        private final Prop prop;
        private final Field field;

        PropInjector(Prop prop, Field field)
        {
            this.prop = prop;
            this.field = field;
            field.setAccessible(true);
        }

        @Override
        public void injectMembers(T instance)
        {
            try {
                Class<?> targetType = field.getType();
                Object val = inProps.as(prop.value(), targetType);
                field.set(instance, val);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
person wener    schedule 12.06.2014