作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在编写一个带有框架的 Web 应用程序,该框架调用我的 Application
类的 run()
方法并传入 Environment< 类型的对象
.
我正在编写的其他对象依赖于此 Environment
类,因为它们需要调用其 register()
和 metrics()
方法.
问题是我在应用程序的 main()
函数中创建对象图,如下所示:
public class MainApplication extends Application<MainConfiguration> {
private final ConnectionPool sharedPool;
public static void main(String[] args) throws Exception {
MainApplication mainApplication = DaggerMainApplicationComponent.create()
.createApplication();
mainApplication.run(args);
}
@Inject public MainApplication(ConnectionPool connectionPool) {
super();
sharedPool = connectionPool;
}
@Override
public void run(MainConfiguration configuration, Environment environment) throws Exception {
// Here is where I have access to the environment variable
}
因此,当 Dagger 构造 MainApplication
时,环境
变量尚未准备好。只有当 run()
被调用时它才可用。
有没有办法将此变量注入(inject)到对象图中?
最佳答案
这类问题已经引起了一些关注here但要回答您的具体情况并详细说明 EpicPandaForce的评论,您可以通过创建持有者类轻松逃脱小型依赖循环:
class EnvironmentHolder {
private Environment environment;
@Nullable
Environment get() {
return environment;
}
void set(Environment environment) {
this.environment = environment;
}
}
并将 Environment
的先前依赖项改为 EnvironmentHolder
的依赖项:
class DependsOnEnvironment {
private final EnvironmentHolder environmentHolder;
@Inject
DependsOnEnvironment(EnvironmentHolder environmentHolder) {
this.environmentHolder = environmentHolder;
}
public void doSomethingWithMetrics() {
Environment environment = environmentHolder.get();
if (environment == null) {
throw new IllegalStateException("Environment object should be available at the injection time of this class");
}
Metrics metrics = environment.metrics();
//etc.
}
}
如果您发现自己经常使用此功能,则可能表明您需要自定义范围。
关于java - 如何将已经存在的对象注入(inject)到 Dagger 2 的对象图中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44313590/
我是一名优秀的程序员,十分优秀!