< plug-in classname="org.springframework.web.struts.ContextLoadPlugin"> < set-property value="WEB-INF/Yhcip.xml,......" property="contextConfigLocation"> < /PLUG-IN> |
3.完成第一种集成方案:实现一个知晓Spring的Action基类.
这种集成方案是从一个公共的能够访问Spring应用上下文的基类中派生所有的Struts Action,但值得庆幸的是:我们不用自己去编写这个知晓Spring应用上下文的基类,因为Spring已经提供了org.springframework.web.struts.ActionSupport:一个org.apache.struts.action.Action的抽象实现.它重载了setServlet()方法以从ContextLoaderPlugin中获取WebapplicationContext.因此,任何时候我们只需要调用super.getBean()方法即可获得一Spring上下文中的一个Bean的引用.
我们再来看一段Action源代码:
public class CourceAction extends ActionSupport { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //取得Spring上下文 ApplicationContext context = super.getWebApplicationContext(); //取得CourceService Bean CourseService courseService = (CourseService) context.getBean("courseService"); Set allCources = courceService.getAllCources(); request.setAttribute("cources", allCources); //..........the other statements. return mapping.findForward("jspView"); }} |
小结
至此,我们已经用第一种方案圆满的完成了Spring与Struts的集成工作.这种集成方式的好处在于直观简洁容易上手.除了需要从ActionSupport中派生,以及需要从应用上下文中获取Bean之外,其他都与在非Spring的Struts中编写和配置Action的方法相似.但这种集成方案也有不利的一面.最为显著的是:我们的Action类将直接使用Spring提供的特定类,这样会使我们的Struts Action(即控制层)的代码与Spring紧密耦合在一起.这是我们不情愿看到的.另外,Action类也负责查找由Spring管理的Bean,这违背了反向控制(IoC)的原则.