当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《上下文初始化时,JSF初始化应用程序范围bean》经验,为你挑选了1个好方法。

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?



1> McDowell..:

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

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

web.xml中:


    appobj.MyApplicationContextListener

执行:

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();
        }
    }

}

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


    
    

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

FacesContext.getCurrentInstance()
            .getExternalContext().getApplicationMap().get("foo");

推荐阅读
小色米虫_524
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有