struts2.x 与 struts1.x 调用 spring 层中的 方法 对比

来源:互联网 发布:sql count 两列 编辑:程序博客网 时间:2024/06/05 22:56

总结下来以备忘记,也希望对其他网友有所帮助。

 

在struts2 中 可以直接通过get 方法来得到spring 接口的实现对象,但要注意的是,接口对象的变量名称要与 applicationContext 配置文件中指定的 ID 的变量名称一致,这样

在struts2的action 中就可以找到,并可直接调用service中的方法。

applicationContext .xml 中的配置如下:

<bean id="teicCmdService" class="com.cast.AYReport.service.impl.TeicCmdServiceImpl">
      <property name="baseDao" ref="baseDao"></property>
 </bean>

action 中的代码

private TeicCmdServiceImpl teicCmdService ;

 

public TeicCmdServiceImpl getTeicCmdService()  { 

            return teicCmdService ;

}

public void setTeicCmdService(TeicCmdServiceImpl  tcs) {

            this.teicCmdService = tcs ;

}

通过以上方式来初始化service对象。

 

 

在struts1中 需要再action中 要先 初始化 WebApplicationContext 而后 在调用它的 getBean(String str) 方法来初始化 spring的接口 从而在调用 service中的实现方法。

 

一下方法可以放到 struts1 的自定义基类中

private WebApplicationContext wac;

public void setServlet(ActionServlet actionServlet) {
  if(actionServlet!=null) {
   super.setServlet(actionServlet);
   ServletContext servletContext = actionServlet.getServletContext();
   wac = WebApplicationContextUtils
   .getRequiredWebApplicationContext(servletContext);
  }
 }

public WebApplicationContext getweb() {
  return wac;
 }

 

子类action 中就可以直接调用父类的 WebApplicationContext  对象的方法来初始化spring了 参考代码如下:

private DdentityManager dManager;

dManager =(DdentityManager)this.getweb().getBean("ddentityManager");

 

上面的bean中的变量ddentityManager要与 applicationContext.xml 中的 ID 一致, 这样即可。

 

注意上面的红色部分。 

原创粉丝点击