0

私の知る限り、FacesContextはリクエストスコープでのみ使用できます。FacesContextのインスタンスを受信しようとするスレッドを作成しましたが、nullを返しています。

私のポイントは、アプリケーションスコープのBeanを10秒ごとに更新することです。

スレッドのrunメソッド:

@Override
public void run()
{
    while (true)
    {
        try
        {
            TimeView timeView = (TimeView)FacesContext.getCurrentInstance().
                    getExternalContext().getApplicationMap().get("timeView"); 
            // FacesContext.getCurrentInstalce() returns null

            timeView.update();
            Thread.sleep(10000);
        }
        catch (InterruptedException ex)
        {
            System.out.println(ex);
        }
    }
}

TimeViewのヘッダー(ゲッター/セッターをスキップしました):

@ManagedBean(eager=true, name="timeView")
@ApplicationScoped
public class TimeView implements Serializable
{
    private int hour;
    private int minutes;
    private int seconds;

    public TimeView()
    {
        update();
    }

    public void update()
    {
        Date date = new Date();
        setHour(date.getHours());
        setMinutes(date.getMinutes());
        setSeconds(date.getSeconds());
    }

faces-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">

    <managed-bean>
        <managed-bean-name>timeView</managed-bean-name>
        <managed-bean-class>foogame.viewBeans.TimeView</managed-bean-class>
        <managed-bean-scope>application</managed-bean-scope>
    </managed-bean>
</faces-config>

それで、このスレッドで私のアプリケーションスコープのBeanへの参照を受け取る方法はありますか?

4

1 に答える 1

1

サーブレット環境外で FacesContext にアクセス/構築する方法があるため、アプリケーション スコープ オブジェクトをワーカー スレッド (バッチ ジョブを実行するスレッド) のコンストラクターに渡すことをお勧めします。スレッド内の参照を更新すると、両方が同じインスタンスを指しているため、アプリケーション スコープの参照が更新されます。

EJB3 環境を使用している場合は、スレッドとスコープを処理する必要なく、EJB タイマー + @Singleton Bean を使用できます。

于 2012-07-23T20:23:52.210 に答える