struts2+spring中action的生命週期問題

將struts2中的action交給spring管理 html

若是沒有指定scope就會出現驗證時第一次驗證的結果一直存在,致使後面的驗證根本沒有進行 web

因此在spring中配置action時要指定scope屬性爲prototype spring

<bean id="randomImageAction"
class="cn.link.sgums.action.RandomImageAction" scope="prototype">
這樣就ok了 session

默認的spring的bean的週期是單態的(Singleton) dom

對於每一次請求不會生成新的實例 測試

 

http://squll.blogbus.com/logs/21755145.html this

Spring裏默認狀況下,用BeanFactory和ApplicationContext得到的bean實例都是一個。看下面這個例子: 
public class HelloBean2 { 
    private String name; 
    private String helloWord; 
    public String getName() { 
       return name; 
    } 
    public void setName(String name) { 
      this.name = name; 
    } 
    public String getHelloWord() {
     return helloWord; 
    } 
    public void setHelloWord(String helloWord) { 
       this.helloWord = helloWord; 
    } 

Bean的定義:
   <bean id="helloBean"
    class="onlyfun.caterpillar.HelloBean2" singleton="true">
     <property name="helloWord" value="test"/>
     <property name="name" value="Tom"/>  
   </bean> prototype


測試 : 
ApplicationContext context = new ClassPathXmlApplicationContext("beans-config.xml"); 
HelloBean2 helloBean1 = (HelloBean2)context.getBean("helloBean"); 
helloBean1.setName("jack"); 
System.out.println(helloBean1.getName()); 
HelloBean2 helloBean2 = (HelloBean2)context.getBean("helloBean"); 
System.out.println(helloBean2.getName()); 
輸出結果爲: jack jack 
由此能夠看出在Spring容器中,默認狀況下,每個bean只有一個實例。
咱們對bean的配置文件作一些修改: 加上了singleton="false" 這個配置,再執行上面的測試,結果爲: jack Tom 這時每次去得到helloBean的實例,就是一個新的實例了。(singleton默認是等於true)。
對於Spring2.0,上面的配置能夠改爲:scope = "prototype" , scope的默認預設值singleton,針對Web應用,scope的值還能夠設置爲「request」,"session","globalSession"分別對應web的請求階段,會話階段,web應用程序階段。 xml

相關文章
相關標籤/搜索