您的位置:IT在中国 >> 在线课堂 >> JSP >> 正文
public class BlogService ...{ private static List<Blog> blogs = new ArrayList<Blog>(); public List<Blog> list() ...{ ... } public Blog create(Blog blog) ...{ ... } public void update(Blog blog) ...{ ... } public void delete(int id) ...{ ... } public Blog findById(int id) ...{ ... } }
BlogService 只是个简单的业务逻辑类,并不是接口,Struts 和 Struts2 的action皆可调用其实例。虽然这样设计在实际项目中会带来不必要的耦合,但我们的例子只是集中在讨论web层上,所以无关重要。
QUOTE:
工具箱: 在第一篇文章中,我们谈论了在Struts2 actions中的依赖注入的接口注入方式。这个是servlet 相关类(HttpServletRequest, HttpServletResponse, PrincipalProxy, 等.)的主要注入方式,但这并不是唯一的方式。
Struts2 可以使用Spring框架作为默认的容器时,依赖注入的setter方法就可用了。通过在action中加入setter方法(如下演示), Struts2 框架将能从Spring框架中获得正确的信息,并通过setter加载在action中。
public void setBlogService(BlogService service) ...{
this.blogService = service;
}
和接口注入方式类似,我们需要一个拦截器来帮助我们完成任务,这就是 ActionAutowiringInterceptor 拦截器。这样我们的业务逻辑类就通过Spring框架管理自动在action被调用之前注入到Struts2得action中。有多种的配置参数(如by name, by type 或 automatically)可供选择,可以让对象和setter匹配的注入的方式根据你的需要而定。