gpt4 book ai didi

java - 如何在实用程序类中使用 Guice 而不是静态方法来配置依赖注入(inject)?

转载 作者:行者123 更新时间:2023-11-30 08:06:46 24 4
gpt4 key购买 nike

我想从实用程序类中删除static内容:

public final class PropertiesUtils {

public static Properties loadProperties(String propFilePath) throws IOException {
Properties properties = new Properties();
try (InputStream in = new FileInputStream(propFilePath)) {
properties.load(in);
}
return properties;
}

我在一个地方使用它:

public class HiveJdbcClient {
public HiveJdbcClient() {
initHiveCredentials();
}

private void initHiveCredentials() {
try {
Properties prop = PropertiesUtils.loadProperties(FileLocations.HIVE_CONFIG_PROPERTIES.getFileLocation());

我已经实现了一些GuiceModulel:

public class GuiceModel extends AbstractModule {    
@Override
protected void configure() {
bind(XpathEvaluator.class).in(Singleton.class);
bind(HiveJdbcClient.class).in(Singleton.class);
bind(QueryConstructor.class).in(Singleton.class);
}
}

我无法理解如何使用 Guice 在此方法中消除静态内容?

我想要下一个签名;

public Properties loadProperties(String propFilePath)

而不是:

public static Properties loadProperties(String propFilePath)

最佳答案

只需将 PropertiesUtils 绑定(bind)添加到 GuiceModel 即可,如下所示:

bind(PropertiesUtils.class).in(Singleton.class);

PropertiesUtils.class

public class PropertiesUtils {

public Properties loadProperties(String propFilePath) throws IOException {
Properties properties = new Properties();
try (InputStream in = new FileInputStream(propFilePath)) {
properties.load(in);
}
return properties;
}

HiveClient.class << 注入(inject) PropertiesUtils

public class HiveJdbcClient {
private final PropertiesUtils props;

@Inject
public HiveJdbcClient(PropertiesUtils props) {
this.props = props;
initHiveCredentials();
}

private void initHiveCredentials() {
try {
Properties prop = props.loadProperties(FileLocations.HIVE_CONFIG_PROPERTIES.getFileLocation());

关于java - 如何在实用程序类中使用 Guice 而不是静态方法来配置依赖注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30991468/

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