1.如果不使用Spring对Struts的Action进行注入时,在struts.xml配置文件中action的class直接配置成类的全路径名,
<action name="*o_o*" class="com.chen.action.{1}Action" method="{2}">
<result >/WEB-INF/view/msg_{2}.jsp</result>
<result name="error" >/WEB-INF/view/msg_error.jsp</result>
</action>
此时虽然可以使用,但是如果我们的action类中包含了其他类的对象,此时我们可以选择使用Spring的注入。
2.当我们使用Spring直接对Struts的Action进行注入时,我的配置为:(此处指使用Annotation进行配置)
Action类的定义
@Component("msgAction")
@Scope("prototype")
public class MsgAction extends ActionSupport implements ModelDriven<SplitPage> {
public MsgBoardService getMsgBoardService() {
return msgBoardService;
}
@Resource(name="msgBoardService")
public void setMsgBoardService(MsgBoardService mbs) {
this.msgBoardService = mbs;
}
private MsgBoardService msgBoardService = null;}
struts.xml文件的配置:
<constant name="struts.objectFactory" value="spring" /><!-- 此标记说明Struts的action由Spring产生 -->
<package name="default" namespace="/" extends="struts-default">
<default-action-ref name="Msgo_oshow" ></default-action-ref>
<action name="*o_o*" class="msgAction" method="{2}">
<result >/WEB-INF/view/msg_{2}.jsp</result>
<result name="error" >/WEB-INF/view/msg_error.jsp</result>
</action>
</package>
一个小问题:当我在action的一个方法中判断this和Spring的getBean()方法获取的对象是否相同时,一直打印false.
代码:
public String show() {
ApplicationContext atx = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println(this == ((MsgAction)atx.getBean("msgAction")));
System.out.println(this.getMsgBoardService() == ((MsgAction)atx.getBean("msgAction")).getMsgBoardService());
msgBoards = msgBoardService.list(splitPage);
return SUCCESS;
}
我就在想为什么会打印出false呢?折腾了一个晚上,原来是因为我设置了@Scope("prototype"),此时当前的这个Action对象是由Spring注入进Struts的,而当我们使用getBean方法时将会new 一个新的Action对象,所以不相等。得了一个小结论,在使用Spring和Struts进行整合时,若使用了Spring对Struts得action进行注入时,我们只需想到当我们访问页面时,Struts直接从Spring的容器中去获取一个新的Action对象就行了。哈哈,我又想多了