Spring3.2.12
Struts2.3.20
看struts代碼:
@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
@ParentPackage("struts-default")
@Namespace("/test")
public class TestAction {
private String flag;
@Action(value = "testAction", results = { @Result(name = "success", location = "/index.jsp") })
public String test() {
System.out.println("request struts.");
try {
WebApplicationContext context = WebApplicationContextUtils
.getWebApplicationContext(ServletActionContext.getServletContext());
TestAction test = context.getBean("testAction", TestAction.class);
System.out.println("this:" + this.flag+"\t" + this);
System.out.println("spring:" + test.flag+"\t" + test);
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
@PostConstruct
public void setFlag() {
this.flag = "From Spring";
}
運行結果:
request struts.
this:From Spring toString:com.me.permission.action.TestAction@732efcfe
spring:From Spring toString:com.me.permission.action.TestAction@2140243b
request struts.
this:From Spring toString:com.me.permission.action.TestAction@11e3c2c6
spring:From Spring toString:com.me.permission.action.TestAction@2140243b
request struts.
this:From Spring toString:com.me.permission.action.TestAction@521d590d
spring:From Spring toString:com.me.permission.action.TestAction@2140243b
運行結果 說明,spring中持有一個TestAction的對象,而且是單例;
請求action的時候,是spring給struts生成的action,但是每一次都是新的,並不是spring所持有的那個單例,這是為什麼哪?
怎麼才能讓spring所持有的那個單例,給struts哪?讓struts每次請求都使用spring中所持有的那個單例。
謝謝各位了,查看了下源碼,發現此處配置有錯誤。
action不需要配置
@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON),
_而struts在通過插件向spring索要action對象的時候,給spring傳遞的是此action的全類名,所以不需要再spring中配置action的bean,spring也可以根據struts提供的全類型找到該bean,並將其實例化,交給struts。