Guice injectMembers method

会有一股神秘感。 提交于 2019-12-05 05:26:22

Why do you need to inject dependencies manually?

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

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

Guice documentation:

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;
    }
}

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!