如何在 JSF 的应用程序级别全局加载 common/re-useable 数据?

How to load common/re-useable data globally at Application Level in JSF?

我正在使用 JSF-2.2、Primefaces-3.5 和 JDK-1.7。

我有一个注册页面,其中有一个关于国家和城市的父子菜单关系,需要根据所选的父值动态加载。

目前我正在显示国家和州的列表!这就像一个魅力! :) How to display list of countries and cities in JSF

我的问题是,如果我们有 n 个用户访问页面,我们将创建 n 个对象,这些对象加载到服务器上。我想减少负载和内存浪费

有没有办法加载数据并将其存储在应用程序的上下文中,并在 JSF 中访问它们。

有用参考:

How to Populate Child Menus in JSF

您可以只从 Balusc 的 answer @ApplicationScoped 制作 bean,并且只使用这个 bean 来读取代码列表。然后您可以将该 bean 注入到您的其他 bean 中,或者直接从 xhtml 中调用它。

您还可以在 init() 中加载城市并保存在 Map<String, List<String>> 中,其中键是国家,值是城市。或者你可以延迟初始化城市:

Map<String, List<String>> map = new HashMap<>();

public synchronized List<String> getCities(String country) {
    if (!map.containsKey(country)) {
        List<String> cities = someService.getCities(country);
        map.put(country, cities);
        return cities;
    }
    return map.get(country);    
}

但是,如果条目有可能随时间变化(例如数据库中的其他系统 updating/deleting),@SessionScoped 可能会更好,因为您不必记住与 @ApplicationScoped.

一样重新加载 application/restart 服务器