Inject variable with custom parameter without creating 2 guice helper interfaces?

前端 未结 1 870
醉梦人生
醉梦人生 2020-12-17 05:19

I\'m using guice to dynamically inject classes in my constructors. For example:

@Inject
public PublisherFrame(EventBus eventBus, MyPublisherService publishSe         


        
相关标签:
1条回答
  • 2020-12-17 05:59

    You don't actually need the additional interface for the class itself (see below). Furthermore, I generally create my factory as a nested interface of the class it creates:

    public class LoginController {
      public interface Factory {
        LoginController create(LoginDialog dlg);
      }
    
      @Inject public LoginController(
          EventBus eventBus,
          MyPublisherService publisherService,
          @Assisted LoginDialog dlg) { /* ... */ }
    }
    
    // in your module
    install(new FactoryModuleBuilder().build(LoginController.Factory.class));
    

    You don't need to call FactoryModuleBuilder.implement unless you want your Factory's factory method's return type to be an interface rather than a concrete class--then Guice won't know what kind of concrete type to construct without your help. In the example below, you couldn't ask FactoryModuleBuilder to simply implement LoginService.Factory for you, as it would have no idea which concrete LoginService implementor to instantiate:

    interface LoginService {
      interface Factory {
        LoginService create(NetConnection connection);
      }
      boolean login(String username, String password);
    }
    
    class SimpleLoginService implements LoginService {
      @Inject SimpleLoginService(@Assisted NetConnection connection) { /* ... */ }
    }
    
    class SecuredLoginService implements LoginService {
      @Inject SecuredLoginService(
          EncryptionService encryptionService,
          @Assisted NetConnection connection) { /* ... */ }
    }
    
    // in your module: implements LoginService.Factory
    install(new FactoryModuleBuilder()
        .implement(LoginService.class, SimpleLoginService.class)
        .build(LoginService.Factory.class));
    // this one implements @Secured LoginService.Factory
    install(new FactoryModuleBuilder()
        .implement(LoginService.class, SecuredLoginService.class)
        .build(Key.get(LoginService.Factory.class, Secured.class));
    

    Barring that, condit's idea of creating a setter method isn't bad, though that does mean that you are constructing your class in a partially-initialized state.

    0 讨论(0)
提交回复
热议问题