2016-03-23 42 views
2

我有兩個管理菜豆,都有一個@ApplicationScope註釋:JSF是建立一個ApplicationScoped bean的兩個實例

Storage.java:

@ManagedBean(eager = true) 
@ApplicationScoped 
public class Storage { 

    private static final Logger LOGGER = LoggerFactory.getLogger(Storage.class); 

    private List<Sheet> sheets = new ArrayList<Sheet>(); 

    public List<Sheet> getSheets() { 
     return sheets; 
    } 

    public Sheet load(String id) { 
     // ... 
    } 

    public void storeSheet(Sheet sheet) { 
     sheets.add(sheet); 
     LOGGER.trace(""+this.hashCode()+" Stored sheet: "+sheet); 
    } 

    public void delete(Sheet s) { 
     sheets.remove(s); 
     LOGGER.trace(""+this.hashCode()+" Removed sheet: "+s); 
    } 

} 

StorageInitializer.java:

@ManagedBean(eager = true) 
@ApplicationScoped 
public class StorageInitializer { 

    @ManagedProperty(value = "#{storage}") 
    private Storage storage; 

    @PostConstruct 
    public void init() { 
     int nofSheets = 10; 
     int min = 20; 
     int max = 200; 
     for (int i=0; i<nofSheets; i++) { 
      storage.storeSheet(new Sheet(
        "Sheet "+i, 
        ThreadLocalRandom.current().nextInt(min, max), 
        ThreadLocalRandom.current().nextInt(min, max))); 
     } 
    } 

    public void setStorage(Storage storage) { 
     this.storage = storage; 
    } 

} 

當應用程序啓動時,StorageInitializer應該將10個實例寫入存儲。其他與@RequestScoped豆類進入商店,使表可見。他們都有一個

@ManagedProperty(value = "#{storage}") 
    private Storage storage; 

來訪問Storage豆。

通過記錄散列,我可以看到我有時會得到兩個Storage bean實例。第一個由StorageInitializer初始化。第二個被@RequestScoped bean使用,並且是空的。

就我而言,這看起來像是一個競賽條件或timinig問題。如果我在StorageInitializer.ini()中設置了一箇中斷點,那麼一切正常。

任何想法?

+0

你是從哪個包導入'@ ApplicationScoped'註釋的? – BalusC

+0

javax.faces.bean.ApplicationScoped – BetaRide

+0

在這兩種情況下?如果所有這些類都處於WAR(因此不是EAR),那麼您的運行時類路徑很可能會受到多個不同版本的JSF庫的污染。檢查並清理它。 – BalusC

回答

0

我有兩個@ApplicationScoped豆與「eager = true」相同的問題。重複的bean位於另一個@ApplicationScoped bean的@ManagedProperty中。我通過將擁有@ManagedProperty的bean的渴望值更改爲false來解決問題。在我的情況下,急切的價值並不是絕對必要的。

+0

您使用的是什麼JSF版本?試過最新的? – Kukeltje

相關問題