如何在实用程序 class 中使用 Guice 而不是静态方法配置依赖注入?

How to configure Dependency Ingection with Guice instead of static method at utility class?

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

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)

在您的代码中添加以下行:

到您的模块(在实际绑定提供者之前):

Map<String, String> bindMap = Maps.newHashMap(Maps.fromProperties(properties));
bindMap.putAll(Maps.fromProperties(System.getProperties()));

Names.bindProperties(binder(), bindMap);

在您的提供商中:

@Inject
@Named("hive.password")
protected String password;

@Inject
@Named("hive.uri")
protected String uri;

您将需要以一种或另一种方式加载属性,但通过这种方式,您不需要知道客户端中属性文件的文件名。一切都在 DI 级别进行管理。

只需将 PropertiesUtils 绑定添加到 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 << 注入 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());