java - Spring - 将自定义实例传递给构造函数

标签 java spring command-query-separation

我正在尝试将命令查询设计模式实现为 基于 MVC spring 的应用程序。

例如,我有一些使用装饰器模式的装饰命令 就像下面这样:

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

如何将这样的处理程序注入(inject)到 Controller 构造函数中?应该在哪里 我实例化这个处理程序?可以实例化它的地方可以是 Controller 构造函数,但这不是最好的解决方案。还有其他想法吗?

谢谢

最佳答案

如果您使用的是 PropertyPlaceholderConfigurer(旧)或 PropertySourcesPlaceholderConfigurer(新),并且您的连接字符串位于 .properties 文件或环境变量中,则可以对连接字符串执行以下操作。您还可以将对象 Autowiring 到配置类中,并使用 @Bean 注释方法来执行 Spring 上下文 xml 的操作。通过这种方法,您可以根据需要创建 bean,并且可以像在 xml 中定义它们一样 Autowiring 它们。

@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)

   }
}

关于java - Spring - 将自定义实例传递给构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24957458/

相关文章:

java - 从方法返回的同步代码中的对象

java - 使用 MyBatis 动态列名与 where 子句中的值进行比较

java - 如何为每个泛型类型创建一个新的 bean 实例?

command-query-separation - 命令查询分离 : commands must return void?

java - 如何将二进制与枚举一起使用?

java - 有没有办法将 @Autowired 变量传递给 Spring Boot 应用程序中的其他类?

java - GetParts() 在 servlet 中返回 null

Spring Cloud - SQS - 此wsdl版本的指定队列不存在

domain-driven-design - 在领域驱动设计的 CQRS 实现中为命令/查询单独应用服务?