g的ContextLoaderListener******,方便Spring与Web容器交互。
紧接着,修改Struts.properties文件,告知Struts 2运行时使用Spring来创建对象(如Action等),内容如下:
struts.objectFactory = spring
清单2 classes\struts.properties
再下来,遵循Spring的原则——面向接口编程,创建接口ChatService,代码如下:
package tutorial;
import java.util.Set;
public interface ChatService {
Set < String > getUserNames();
}
在Struts 2中实现IoC模式(3)
时间:2011-04-11
清单3 tutorial.ChatService.java
然后,再创建一个默认实现ChatServiceImpl,代码如下:
package tutorial;
import java.util.HashSet;
import java.util.Set;
public class ChatServiceImpl implements ChatService {
public Set < String > getUserNames() {
Set < String > users = new HashSet < String > ();
users.add( " Max " );
users.add( " Scott " );
users.add( " Bob " );
return users;
}
}
清单4 tutorial.ChatServiceImpl.java
接下来,就该新建Action了。tutorial.ChatAction.java的代码如下:
package tutorial;
import java.util.Set;
import com.opensymphony.xwork2.ActionSupport;
public class ChatAction extends ActionSupport {
private static final long serialVersionUID = 8445871212065L ;
private ChatService chatService;
private Set < String > userNames;
public void setChatService(ChatService chatService) {
this .chatService = chatService;
}
public Set < String > getUserNames() {
return userNames;
}
@Override
public String execute() {
userNames = chatService.getUserNames();
return SUCCESS;
}
}
在Struts 2中实现IoC模式(4)
时间:2011-04-11
清单5 tutorial.ChatAction.java
ChatAction类使用属性(Getter/Setter)注入法取得ChatService对象。
然后,配置Spring的applicationContext.xml(位于WEB-INF下)文件,内容如下:
<? xml version="1.0" encoding="UTF-8" ?>
< beans xmlns ="http://www.springframework.org/schema/beans"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd" >
< bean id ="chatService" class ="tutorial.ChatServiceImpl" />
< bean id ="chatAction" class ="tutorial.ChatAction" scope ="prototype" >
< property name ="chatService" >
< ref local ="chatService" />
</ property >
</ bean >
</ beans >
清单6 WEB-INF\applicationContext.xml
上述代码有二点值得大家注意的:
Struts 2会为每一个请求创建一个Action对象,所以在定义chatAction时,使用scope="prototype"。这样Spring就会每次都返回一个新的ChatAction对象了;
因为ChatServiceImpl被配置为默认的scope(也即是singleton,唯一的),所以在实现时应保证其线程安全(关于编写线程安全的代码的讨论已经超出本文的范围,更超出了本人的能力范围,大家可以参考Addison Wesley Professional出版的《Java Concurrency in Practice》)。
接下来,在classes/struts.xml中配置Action,内容如下:
<! DOCTYPE struts PUBLI
|