Guice injectMembers method

这一生的挚爱 提交于 2019-12-10 03:59:52

问题


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()??

回答1:


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.



来源:https://stackoverflow.com/questions/5116383/guice-injectmembers-method

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