2011-07-07 51 views
1

如何在JSF 1.2和更新版本中模擬JSF 1.1中的@postConstruct行爲?JSF 1.1 @postConstruct

其實,我想在頁面加載時自動調用一個bean方法?

我在JSF 1.1上使用IceFaces 1.8。

回答

2

@PostConstruct的要點是提供一種鉤後所有管理屬性(如在<managed-property>@ManagedProperty)被設定和所有依賴注射(例如@EJB@Resource@Inject等)已經採取措施來執行一些代碼地點。

如果你沒有它們,只要使用bean的構造函數即可。

public class Bean { 

    public Bean() { 
     // Just do your job here. Don't do it the hard way. 
    } 

    // ... 
} 

或者,如果你真的想在一個特定的屬性已被設置爲執行它,然後做在二傳手的工作,而空檢查當前屬性值。

public class Bean { 

    private SomeObject someManagedProperty; 

    public void setSomeManagedProperty(someManagedProperty) { 
     if (this.someManagedProperty == null && someManagedProperty != null) { 
      // First-time set, now you can do your job here. 
     } 

     this.someManagedProperty = someManagedProperty; 
    } 

    // ... 
} 

更新按照評論:

我的意思是每一個頁面加載的時間來執行方法

@PostConstruct不會做那。但是,如果bean被請求作用域,那麼您將看到相同的效果。您似乎在使用會話或應用程序範圍的託管bean來管理請求範圍的數據。這實質上是錯誤的。您應該將其轉換爲請求範圍的bean。任何real會話範圍的數據可以分成一個會話範圍的bean,然後通過<managed-property>注入。

+0

謝謝你,但我打算每次頁面加載時執行該方法 – Moro