0

I'm trying to implement a command-query design pattern into a MVC spring based application.

I have, for example, some decorated commands using decorator pattern like bellow:

ICommandHandler handler =
    new DeadlockRetryCommandHandlerDecorator<MoveCustomerCommand>(
        new TransactionCommandHandlerDecorator<MoveCustomerCommand>(
            new MoveCustomerCommandHandler(
                new EntityFrameworkUnitOfWork(connectionString),
                // Inject other dependencies for the handler here
            )
        )
    );

How can I inject such a handler into a controller constructor? Where should I instantiate this handler? A place where this can be instantiated can be the controller constructor, but this isn't the best solution. Any other ideeas?

Thanks

4

1 回答 1

1

If you're using PropertyPlaceholderConfigurer (old) or PropertySourcesPlaceholderConfigurer (new), and your connection string is in a .properties file or environment variable you can do the following for the connection string. You can also autowire objects into a configuration class and annotate a method with @Bean to do what the Spring context xml does. With this approach you can create your beans as you wish and they're available to autowire just like you defined them in xml.

@Configuration
public class MyAppConfig {

   @Autowired private MyType somethingToAutowire;

   @Bean
   public ICommandHandler iCommandHandler(@Value("${datasource.connectionString}") 
                                                  final String connectionString) {

       return new DeadlockRetryCommandHandlerDecorator<MoveCustomerCommand>();

       // You obviously have access to anything autowired in your configuration
       // class.  Then you can @Autowire a ICommandHandler type into one of your 
       // beans and this method will be called to create the ICommandHandler (depending on bean scope)

   }
}
于 2014-07-26T00:33:10.777 回答