Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

java - Refresh/Reload Application scope managed 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

data.reload();

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

}

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...