Java 怎么返回存储在应用程序作用域中指定名称下的任何JSF bean

2019年8月13日22:06:05 评论 32

1.简介

Java 怎么返回存储在应用程序作用域中指定名称下的任何JSF bean?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

 
import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;

public class Main{
    public static void main(String[] argv) throws Exception{
        Class cls = String.class;
        System.out.println(getApplicationBean(cls));
    }
    private static Logger logger = Logger.getLogger(BeanHelper.class);
    
    public static Object getApplicationBean(final Class<?> cls) {
        String name = null;
        name = cls.getSimpleName();
        Object result = FacesContext.getCurrentInstance()
                .getExternalContext().getApplicationMap().get(name);
        logger.debug("Getting bean " + name + ": " + result);
        if (result == null) {
            result = addApplicationBean(cls, name);
        }
        return result;
    }
    
    private static synchronized Object addApplicationBean(
            final Class<?> cls, String name) {
        Object result = FacesContext.getCurrentInstance()
                .getExternalContext().getApplicationMap().get(name);
        if (result != null)
            return result;
        try {
            logger.debug("Creating new session bean: " + name);
            Object newBean = cls.newInstance();
            FacesContext.getCurrentInstance().getExternalContext()
                    .getApplicationMap().put(name, newBean);
            return newBean;
        } catch (Exception e) {
            throw new RuntimeException("Error creating new bean of type "
                    + cls, e);
        }
    }
}

 

3.总结

示例代码演示了 Java 怎么返回存储在应用程序作用域中指定名称下的任何JSF bean,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: