Struts与Spring整合:bbp project

来源:互联网 发布:windows 10 for phone 编辑:程序博客网 时间:2024/06/12 01:04

(注:在我的opensource里,还struts与spring的三种整合方式,都很好,是我转载别人的,在看他们俩整合时,不要忘记参看。)

our project user spring and structs method summerize:

 

1、首先,我们在struts-config.xml文件中,存在以下语句,目的是把struts动作委托给一个类来处理:

    <action-mappings>                                          (注:type的书写是正常的)

      <action path="/search/user" parameter="type" type="com.innov8tion.action.UserAction" scope="request">
      <forward name="user" path="/search/user.jsp" redirect="false" />
      </action>                                                      

    </action-mappings>

    

    <controller processorClass="com.innov8tion.action.ServiceAutowireRequestProcessor" />   //重要

 

2、写ServiceAutowireRequestProcessor类:

import org.apache.struts.action.RequestProcessor;

public class ServiceAutowireRequestProcessor extends RequestProcessor {
     /**
      * Override the base class method to return the autowireService action.
      */
     protected Action processActionCreate(HttpServletRequest request,
           HttpServletResponse response, ActionMapping mapping)
           throws IOException {
          Action action = super.processActionCreate(request, response, mapping); //用Struts创建默认的action
          autowireService(action);                                                             //用spring注入action中的属性
          return action;
     }

     private void autowireService(Action action) {
  
          ServiceLocator.getInstance(action).autowireService(action);    //ServiceLocator是我们自己写的类。
     }

}

 

public final class ServiceLocator {

     private static ServiceLocator instance = null;

     private ApplicationContext context = null;

     /**
      * Create a new ServiceLocator Instance.
      */
     private ServiceLocator(ApplicationContext context) {
          this.context = context;
     }

     /**
      * @return ServiceLocator Instance
      */
     public static ServiceLocator getInstance(Action action) {
          ServletContext servletContext = action.getServlet().getServletContext();

          if(instance == null){   
               ApplicationContext ctx = WebApplicationContextUtils.
                    getRequiredWebApplicationContext(servletContext);
               instance = new ServiceLocator(ctx);
         }
  
          return instance;
     }

     public void autowireService(Object bean) {
          ((AbstractApplicationContext) context).getBeanFactory()
                .autowireBeanProperties(bean,
                    AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
     }

}

 

总结:

     1. 在ServiceLocator类中的autowireService方法,目的是使用spring IOC自动绑定功能来注入action中的属性。

    2. 在ServiceAutowireRequestProcessor  类中的processActionCreate方法,我觉得其不仅让struts与spring耦合很小,而且在spring配置文件中,省写了struts的action的配置

原创粉丝点击