我想从实用程序类中删除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属性loadProperties(String propFilePath)
答案 0 :(得分:1)
只需将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());
答案 1 :(得分:0)
在代码中添加以下行:
到您的模块(在实际绑定提供者之前):
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级别进行管理。