Struts integrates spring的好处就是解除 hard-code,如下是Struts官网给出的integrate spring的理由:
- If I need to replace the EditServiceInMemory with another class that implements the EditService interface I'll have to hunt down and replace all statements where I hard-coded the dependency.
- I cannot test EditAction without using the EditServiceInMemory class. I cannot isolate EditAction by using a stub implementation of EditService when writing my test case because the use of EditServiceInMemory is hard-coded.
这个integration主要有两种方式:
第一种、借助struts2-spring-plugin-x.x.x.jar通过spring来管理、生成和autowriting(自动组装)actionsport依赖的类实例。这种方式的action还是Struts自己来管理的,并没有registe到spring中。
要通过spring来autowriting依赖关系,也照样是需要相应的get和set方法的。
public class StrutsSpringTestAction extends ActionSupport
{
private Struts2SpringTestInterface install;
public Struts2SpringTestInterface getInstall() {
return install;
}
public void setInstall(Struts2SpringTestInterface install) {
this.install = install;
}
@Override
public String execute() throws Exception {
return super.execute();
}
}
然后在spring的配置文件applicationContext.xml中注册被依赖对象Struts2SpringTestInterface
<bean id="install" class="com.cmpsky.strutstest.server.Struts2SpringTestImpl">
</bean>
注意这里的beanId 为install,这个与Action中的属性install是同名的,spring的默认autowriting就是 by name的方式的(所以它俩的相同)。
由于这里的action并没有托管到spring,所以不需要spring中注册StrutsSpringTestAction 。
在struts.xml中再配置好action就OK了
<action name="struts2spring" class="com.cmpsky.strutstest.action.struts2spring.StrutsSpringTestAction">
<result name="success">/struts2springResult.jsp</result>
</action>
关于spring的autowriting有如下几种方式:
The autowire
property can be set to several options.
name | Auto-wire by matching the name of the bean in Spring with the name of the property in your action. This is the default |
---|---|
type | Auto-wire by looking for a bean registered with Spring of the same type as the property in your action. This requires you to have only one bean of this type registered with Spring |
auto | Spring will attempt to auto-detect the best method for auto-wiring your action |
constructor | Spring will auto-wire the parameters of the bean's constructor |
no | Turn off externally defined autowiring. Annotation-driven injection and injection based on Springs *Aware-interfaces still applies |
struts.objectFactory.spring.autoWire = type
|
还有一种方式就是:把action注册在spring中管理,这就不需要struts2-spring-plugin-x.x.x.jar这个插件了。Struts官网是把这个作为一个alternative来介绍的。
1、在spring的applicationContext.xml中完成如下配置:
<span style="white-space:pre"> </span><bean id="install" class="com.cmpsky.strutstest.server.Struts2SpringTestImpl">
</bean>
<bean id="noPlugin" class="com.cmpsky.strutstest.action.struts2spring.StrutsSpringTestAction">
<property name="install" ref="install"></property>
</bean>
<span style="white-space:pre"> </span><action name="noplugin" class="noPlugin">
<result name="success">/struts2springResult.jsp</result>
</action>
注意
class="noPlugin"的值和
<bean id="noPlugin" 的值都为noPlugin是有映射关系的。
然后就又OK了!