Guice injectMembers方法 [英] Guice injectMembers method

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

问题描述

我了解使用构造函数注入优于setter注入的好处,但在某些情况下,我只必须坚持基于setter的注入.我的问题是如何使用jector.injectMembers()方法注入所有基于setter的注入类的成员?

I understand the benefits of using constructor injection over setter injection but in some cases I have to stick with setter-based injection only. My question is how to inject members of all the setter-based injection classes using injector.injectMembers() method?

//I am calling this method in init method of my application
private static final Injector injector = Guice.createInjector(new A(), new B());

//Injecting dependencies using setters of all classes bound in modules A and B
injector.injectAllMembers()??

推荐答案

为什么需要手动注入依赖项?

Why do you need to inject dependencies manually?

Guice自动将依赖项注入到字段和方法中. 使用:

Guice injects dependencies into the fields and methods automatically. Use:

YourClass yourClass = injector.getInstance(YourClass.class);

指导文档:

每当Guice创建一个实例时,它都会 自动执行此注射 (先执行构造函数 注射),所以如果您能够 Guice为您创建所有对象, 您将永远不需要使用此方法.

Whenever Guice creates an instance, it performs this injection automatically (after first performing constructor injection), so if you're able to let Guice create all your objects for you, you'll never need to use this method.

您只需将成员自己注入到手动创建的实例中,如下所示:

You need to inject members by yourself only into a manually created instance like this:

YourClass yourClass = new YourClass();
injector.injectMembers(yourClass);

或者您可以使用类似的东西:

Or you can use something like that:

public class YourClassProvider implements Provider<YourClass> {

    private final Injector injector;

    @Inject
    public YourClassProvider(Injector injector) {
        this.injector = injector;
    }

    public YourClass get() {

        YourClass yourClass = new YourClass();
        injector.injectMembers(yourClass);

        return yourClass;
    }
}

在任何情况下,YourClass的设置方法都应使用@Inject注释.

In any case, setters of YourClass should be annotated with @Inject.

这篇关于Guice injectMembers方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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