使用Google Guice在运行时创建对象

时间:2018-10-18 17:23:51

标签: dependency-injection guice

我正在构建一个应用程序,代表我的用户从其AWS帐户中下载S3和DynamoDB中的文件。每个用户都首先在我的系统中注册其AWS账户详细信息。

当我的应用程序启动时,我将读取所有用户信息,并根据他们所注册的用户为他们创建一个S3Client或DyanmoDBClient。在运行时,我使用其注册的帐户详细信息检索对象。代码看起来像这样。

interface ReaderClient {
  public Object read();
}

public class S3Client implements ReaderClient {
  getInstance(account);
}

public class DynamoDBClient implements ReaderClient {
  getInstance(account);
}

class ReaderClientFactory {
  public static ReaderClient getReaderClient(User) {
    switch(user.database) {
        case S3:
            return S3Client.getInstance(user.account);
            break;
        case Dynamo:
            return DynamoDBClient.getInstance(user.account)
            break
    }
  }

}

如何用Google guice替换该工厂?这有可能吗? 我通过提供程序进行了挖掘,并协助注入,但无法适应此用例。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

 public class Main {
public static void main(String[]args){ReaderClientFactory factory = Guice.createInjector(new ReaderClientModule(user).getInstance(ReaderClientFactory.class));
    ReaderClient client = factory.create();}}interface ReaderClient {public Object read();}class S3Client implements ReaderClient {
public Object read(){
    System.out.println("S3 Client");
    return new Object();
}}class DynamoDBClient implements ReaderClient {
public Object read(){
    System.out.println("Dynamo DB Client");
    return new Object();
}}interface ReaderClientFactory {
public ReaderClient create();}class ReaderClientModule extends AbstractModule{

User user;

@Inject
ReaderClientModule(@Assited User user){
    this.user = user;
}

@Override
protected void configure(){
    switch(user.database){
        case S3:
           install(new FactoryModuleBuilder()
           .implement(ReaderClient.class, S3Client.class)
           .build(ReaderClientFactory.class));
           break:
        case Dynamo:
            install(new FactoryModuleBuilder()
                    .implement(ReaderClient.class, DynamoDBClient.class)
                    .build(ReaderClientFactory.class
            break;      
    }}  }