上下文初始化时,JSF初始化应用程序范围bean

Mat*_*inn 16 java jsf

I'm building a JSF+Facelets web app, one piece of which is a method that scans a directory every so often and indexes any changes. This method is part of a bean which is in application scope. I have built a subclass of TimerTask to call the method every X milliseconds. My problem is getting the bean initialized. I can reference the bean on a page, and when I go to the page, the bean is initialized, and works as directed; what I would like instead is for the bean to be initialized when the web context is initialized, so that it doesn't require a page visit to start the indexing method. Google has shown a few people that want this functionality, but no real solutions outside of integrating with Spring, which I really don't want to do just to get this piece of functionality.

我已经尝试过使用"load-on-startup"设置的servlet和一个ServletContextListener来解决问题,并且无法正确设置,因为没有FacesContext可用,或者因为我无法从JSF环境引用bean.

有没有办法在Web应用程序启动时初始化JSF bean?

McD*_*ell 14

如果您的代码调用FacesContext,它将无法在与JSF请求生命周期关联的线程之外工作.为每个请求创建一个FacesContext对象,并将其置于请求的末尾.您可以通过静态调用获取它的原因是因为它在请求开始时设置为ThreadLocal.FacesContext的生命周期与ServletContext的生命周期无关.

也许这还不够(听起来你已经走了这条路),但是你应该能够使用ServletContextListener来做你想做的事情.只需确保对FacesContext的任何调用都保存在JSP的请求线程中.

web.xml中:

<listener>
    <listener-class>appobj.MyApplicationContextListener</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)

执行:

public class MyApplicationContextListener implements ServletContextListener {

    private static final String FOO = "foo";

    public void contextInitialized(ServletContextEvent event) {
        MyObject myObject = new MyObject();
        event.getServletContext().setAttribute(FOO, myObject);
    }

    public void contextDestroyed(ServletContextEvent event) {
        MyObject myObject = (MyObject) event.getServletContext().getAttribute(
                FOO);
        try {
            event.getServletContext().removeAttribute(FOO);
        } finally {
            myObject.dispose();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

您可以通过JSF应用程序范围来解决此对象(或者如果没有其他变量存在同名,则直接解决):

<f:view>
    <h:outputText value="#{applicationScope.foo.value}" />
    <h:outputText value="#{foo.value}" />
</f:view>
Run Code Online (Sandbox Code Playgroud)

如果您希望在JSF托管bean中检索对象,可以从ExternalContext获取它:

FacesContext.getCurrentInstance()
            .getExternalContext().getApplicationMap().get("foo");
Run Code Online (Sandbox Code Playgroud)