我有一个旧的struts系统,移植到了Grails上,现在想从struts的Action中调用Grails的Service.
先在旧系统中新建一个Interface
public interface IUserService {
public List doSomething(Integer userId);
}
然后用grails create-service user 来创建一个UserService.groovy,并实现IUserService接口
//groovy code
import com.xxx.service.IUserService
class UserService implements IUserService {
boolean transactional = true
static scope = "singleton"
public List doSomething(Integer userId) {
...
return aList
}
}
然后在Struts Action或action的父类里添加下面方法
//javaeye好像不支持尖括号,这里改成方括号
protected [T] T getBean(String name) {
Assert.notNull(name);
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
return (T) ctx.getBean(name);
}
然后在Action里这样使用
IUserService userService = getBean("userService");
List aList = userService.doSomething(123);
其实,这就是在action中调用了Spring容器中的一个Bean, Grails将service放在Spring容器中。