我正在尝试将命令查询设计模式实现为 基于 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/