2012-07-23 65 views
0

据我所知,FacesContext仅在请求范围内才可用。我创建了一个尝试接收FacesContext实例的线程,但它返回null。JSF接收FacesContext外部请求

我的意思是每10秒更新一些应用程序范围的bean。

线程的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的头(我已经跳过getter/setter方法):

@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的引用吗?

+0

您使用ejbs吗? – 2012-07-23 14:29:16

+0

我不知道它是什么。 – 2012-07-23 14:57:13

回答

1

由于现在有方法可以在Servlet环境之外访问/构造FacesContext,我建议您将应用程序作用域对象传递给工作线程(执行批处理作业的线程)的构造函数。更新线程中的引用将导致更新应用程序作用域引用,因为它们都指向同一个实例。

如果你有一个EJB3环境,你可以使用EJB timer + @Singleton bean,而不需要处理线程和范围。