gpt4 book ai didi

java - 如何将我的类的实例注入(inject)另一个类?

转载 作者:行者123 更新时间:2023-12-02 08:54:29 25 4
gpt4 key购买 nike

我正在使用play Framework 2.8.x,我需要将我的配置类注入(inject)另一个类,并且我已经编写了用于创建配置的自定义模块。我的模块如下所示:

public class ConfigModule extends AbstractModule {
private Config config;

public ConfigModule(Environment environment, Config config) {
this.config = config;
}

@Override
protected void configure() {
bindRedisConfig();
}

void bindRedisConfig() {
System.out.println("LOAD");
RedisConfig redisConfig = new RedisConfig(
config.getString("configuration.redis.host")
, config.getInt("configuration.redis.port")
, config.getString("configuration.redis.password")
, config.getString("configuration.redis.domain")
);
bind(RedisConfig.class).annotatedWith(Names.named(Constant.CONFIG_REDIS)).toInstance(redisConfig);
}
}

我尝试像这样注入(inject)它:

public class ProcessDataStore {
private final JedisPool jedisPool;
private final RedisConfig config;

@Inject
public ProcessDataStore(RedisConfig config) {
this.config = config;
}
}

我的配置类非常简单:

@Singleton
public class RedisConfig {
public final String host;
public final int port;
public final String password;
public final String domain;

public RedisConfig(String host, int port, String password, String domain) {
this.host = host;
this.port = port;
this.password = password;
this.domain = domain;
}
}

但是当我运行我的应用程序时,出现异常:

1) Could not find a suitable constructor in config.RedisConfig. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.
at config.RedisConfig.class(RedisConfig.java:17)
while locating config.RedisConfig
for the 1st parameter of repository.ProcessDataStore.<init>(ProcessDataStore.java:25)
while locating repository.ProcessDataStore
for field at controllers.DashboardController.db(DashboardController.java:19)
while locating controllers.DashboardController
for the 5th parameter of router.Routes.<init>(Routes.scala:38)
at play.api.inject.RoutesProvider$.bindingsFromConfiguration(BuiltinModule.scala:137):
Binding(class router.Routes to self) (via modules: com.google.inject.util.Modules$OverrideModule -> play.api.inject.guice.GuiceableModuleConversions$$anon$4)

如果我创建不带参数的默认构造函数,我的应用程序不会引发任何异常,但注入(inject)的 RedisConfig 为空。我将模块加载到我的应用程序中:

play.modules.enabled += "modules.ConfigModule"

我能做错什么吗?

最佳答案

我看到 2 件可疑的事情。

1) RedisConfig 类上的 @Singleton 注释。它可以使注入(inject)器创建并注入(inject) RedisConfig 类的新实例,而不是 redisConfig

2) 绑定(bind)定义包含.annotatedWith(Names.named(Constant.CONFIG_REDIS))。因此ProcessDataStore的构造函数参数应该用@Named注释:

 @Inject
public ProcessDataStore( @Named(Constant.CONFIG_REDIS) RedisConfig config) {...}

关于java - 如何将我的类的实例注入(inject)另一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60567877/

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