刷新/重新加载应用程序范围托管 bean [英] Refresh/Reload Application scope managed bean

查看:19
本文介绍了刷新/重新加载应用程序范围托管 bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在刷新或重新加载应用程序范围的托管 bean 时遇到问题.它表现为缓存数据 bean.因此,一旦 db 端的数据发生更改,我想重新加载 bean 中的列表.无论如何要刷新/重新加载列表,例如根据给定时间每天一次?谢谢

I have a problem to refresh or reload an application scoped managed bean. It behaves as cached data bean. So once data is changed on db side, i want to reload the the list in the bean. Is there anyway to refresh/reload the list, say once a day based on given time? Thanks

推荐答案

只需向应用程序作用域 bean 添加一个方法即可.

Just add a method to the aplication scoped bean which does exactly that.

public void reload() {
    list = dao.list();
}

然后在另一个 bean 中抓取/注入这个 bean 并调用该方法.

Then grab/inject this bean in another bean and call the method.

data.reload();

<小时>

更新抱歉,我忽略了一天一次".你的意思是在后台自动重新加载?这最好通过由 ScheduledExecutorService.创建一个 ServletContextListener 如下:


Update sorry, I overlooked the "once a day" bit. You mean automatic reloading in the background? This is best to be achieved by a background thread which is managed by ScheduledExecutorService. Create a ServletContextListener like follows:

@WebListener
public class Config implements ServletContextListener {

    private ScheduledExecutorService scheduler;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        Reloader reloader = new Reloader(event.getServletContext());
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(reloader, 1, 1, TimeUnit.DAYS);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        scheduler.shutdownNow();
    }

}

其中Reloader类看起来像这样(假设托管bean名称是data)

Where the class Reloader look like this (assuming that the managed bean name is data)

public class Reloader implements Runnable {

    private ServletContext context;

    public Reloader(ServletContext context) {
        this.context = context;
    }

    @Override
    public void run() {
        Data data = (Data) context.getAttribute("data");
        if (data != null) {
            data.reload();
        }
    }

}

这篇关于刷新/重新加载应用程序范围托管 bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆