Using @Assisted injection with multiple parameters of the same type (@Named params)

my problem boils down to using @Assisted with two string arguments for factory. The problem is that since Guice treats the type as a mechanism for identifying parameters, both parameters are the same, and I get a configuration error.

The code:

public class FilePathSolicitingDialog { //... some fields public static interface Factory { public FilePathSolicitingDialog make(Path existingPath, String allowedFileExtension, String dialogTitle); } @Inject public FilePathSolicitingDialog(EventBus eventBus, SelectPathAndSetTextListener.Factory listenerFactory, FilePathDialogView view, @Assisted Path existingPath, @Assisted String allowedFileExtension, @Assisted String dialogTitle) { //... typical ctor, this.thing = thing } // ... methods } 

The problem is two-line parameters.

I tried marking each line with separate @Named annotations ("as needed"), but this just leads to more configuration errors. From the sound of these errors, they donโ€™t want to bind annotations to the factory class, so I havenโ€™t tried custom anchor annotations.

A simple and noisy solution is to create a simple class of arguments that contains these three auxiliary values, and simply introduces the following:

  public static class Config{ private final Path existingPath; private final String allowedFileExtension; private final String dialogTitle; public Config(Path existingPath, String allowedFileExtension, String dialogTitle){ this.existingPath = existingPath; this.allowedFileExtension = allowedFileExtension; this.dialogTitle = dialogTitle; } } public static interface Factory { public FilePathSolicitingDialogController make(Config config); } @Inject public FilePathSolicitingDialogController(EventBus eventBus, SelectPathAndSetTextListener.Factory listenerFactory, FilePathDialogView view, @Assisted Config config) { //reasonably standard ctor, some this.thing = thing // other this.thing = config.thing } } 

It works and is likely to be pretty hopeless, but noisy. Some way to get rid of this nested static class would be nice.

Thanks for any help!

+9
java dependency-injection guice
May 08 '14 at 10:45
source share
1 answer

Check out this documentation (earlier here ):

Selection of parameter types

The types of factory method parameters must be different. To use multiple parameters of the same type, use an annotation named @Assisted to disambiguate the parameters. Names should be applied to factory method parameters:

 public interface PaymentFactory { Payment create( @Assisted("startDate") Date startDate, @Assisted("dueDate") Date dueDate, Money amount); } 

... and constructor parameters of a specific type:

 public class RealPayment implements Payment { @Inject public RealPayment( CreditService creditService, AuthService authService, @Assisted("startDate") Date startDate, @Assisted("dueDate") Date dueDate, @Assisted Money amount) { ... } } 
+18
May 8 '14 at 23:51
source share



All Articles