【发布时间】:2010-01-26 15:19:54
【问题描述】:
在我当前的项目中,我正在处理实现大型接口的 EJB。 实现是通过业务委托完成的,业务委托实现相同的接口并包含真实的业务代码。
正如一些文章所建议的那样
- http://code.google.com/intl/fr/events/io/2009/sessions/GoogleWebToolkitBestPractices.html
- http://www.nofluffjuststuff.com/conference/boston/2008/04/session?id=10150
这个“命令模式”的使用顺序是
- 客户端创建一个命令并对其进行参数化
- 客户端向服务器发送命令
- 可以提供服务器接收命令、日志、审计和断言命令
- 服务器执行命令
- 服务器返回命令结果给客户端
问题发生在第 4 步:
现在我正在使用 spring 上下文从命令内部的上下文中获取 bean, 但我想将依赖项注入到命令中。
这是一个用于说明目的的幼稚用法。我在有问题的地方添加了 cmets:
public class SaladCommand implements Command<Salad> {
String request;
public SaladBarCommand(String request) {this.request = request;}
public Salad execute() {
//this server side service is hidden from client, and I want to inject it instead of retrieving it
SaladBarService saladBarService = SpringServerContext.getBean("saladBarService");
Salad salad = saladBarService.prepareSalad(request);
return salad;
}
}
public class SandwichCommand implements Command<Sandwich> {
String request;
public SandwichCommand(String request) {this.request = request;}
public Sandwich execute() {
//this server side service is hidden from client, and I want to inject it instead of retrieving it
SandwichService sandwichService = SpringServerContext.getBean("sandwichService");
Sandwich sandwich = sandwichService.prepareSandwich(request);
return sandwich;
}
}
public class HungryClient {
public static void main(String[] args) {
RestaurantService restaurantService = SpringClientContext.getBean("restaurantService");
Salad salad = restaurantService.execute(new SaladBarCommand(
"chicken, tomato, cheese"
));
eat(salad);
Sandwich sandwich = restaurantService.execute(new SandwichCommand(
"bacon, lettuce, tomato"
));
eat(sandwich);
}
}
public class RestaurantService {
public <T> execute(Command<T> command) {
return command.execute();
}
}
我想摆脱像SandwichService sandwichService = SpringServerContext.getBean("sandwichService"); 这样的电话
而是让我的服务注入。
如何做到这一点最简单?
【问题讨论】:
-
这个问题真的与 EJB 有关吗?似乎您只是在问如何在 Spring 中连接事物。
SampleCommand是什么?谁实例化它?谁使用它?这是什么? -
在 skaffman 发表评论后,我已更新我的问题以进行澄清。
-
如果你曾经为这个问题实现过一些东西,我很想听听。我对执行客户端不需要关心的命令所需的服务端服务有同样的问题。
-
@Jaapjan,不抱歉:我只是保留了说明我的示例的设计:命令正在从上下文中提取服务。使用注解应该可以解决这类问题
标签: java spring client-server command-pattern