gpt4 book ai didi

Guice injectMembers 方法

转载 作者:行者123 更新时间:2023-12-04 10:57:32 26 4
gpt4 key购买 nike

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

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

最佳答案

为什么需要手动注入(inject)依赖?

Guice 会自动将依赖项注入(inject)到字段和方法中。
采用:

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

吉斯文档:

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.



您只需要自己将成员注入(inject)到手动创建的实例中,如下所示:
YourClass yourClass = new YourClass();
injector.injectMembers(yourClass);

或者你可以使用类似的东西:
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 的 setter 都应该使用@Inject 进行注释。

关于Guice injectMembers 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5116383/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com