Guice动态注入自定义注释 [英] Guice dynamic inject with custom annotation

查看:113
本文介绍了Guice动态注入自定义注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些资源,但我不能迭代它并将它们全部绑定,
我必须使用密钥来请求资源。所以,我必须动态注入。

I have some resource, but I can not iterator it and bind them all, I have to use the key to request the resource.So, I have to dynamic inject.

我定义了一个注释,如

@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注释的注入我需要知道
注入字段和注释。

I have to handle the injection annotated by @Res and I need to know the inject field and the annotation.

这可能在 Guice 以及如何?即使使用spi?

Is this possible in Guice and how ? even with spi ?

推荐答案

我按照 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);
            }
        }
    }
}

这篇关于Guice动态注入自定义注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆