在我当前的项目中,我正在处理实现巨大接口的 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,但是我想将依赖项注入到命令中。
这是用于说明目的的幼稚用法。我在有问题的地方添加了评论:
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");
并注入我的服务。
如何做到这一点最简单的方法?