หน้าเว็บ

วันอังคารที่ 4 ธันวาคม พ.ศ. 2555

JSF(JavaServer Faces) get service by WebApplicationContextUtiles : spring

package com.blogspot.na5cent.utils;

import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.jsf.FacesContextUtils;

/**
 *
 * @author Redcrow
 */
public class JSFSpringUtils {

    public static <T> T getBean(Class<T> clazz) {
        ServletContext servletContext = FacesContextUtils
               .getRequiredWebApplicationContext(FacesContext.getCurrentInstance())
               .getServletContext();
        return WebApplicationContextUtils
               .getWebApplicationContext(servletContext)
               .getBean(clazz);
    }

    public static Object getBean(String bean) {
        ServletContext servletContext = FacesContextUtils
               .getRequiredWebApplicationContext(FacesContext.getCurrentInstance())
               .getServletContext();
        return WebApplicationContextUtils
               .getWebApplicationContext(servletContext)
               .getBean(bean);
    }

    public static <T> T getBean(ServletContext servletContext, Class<T> clazz) {
        return WebApplicationContextUtils
               .getWebApplicationContext(servletContext)
               .getBean(clazz);
    }

    public static Object getBean(ServletContext servletContext, String bean) {
        return WebApplicationContextUtils
               .getWebApplicationContext(servletContext)
               .getBean(bean);
    }
}

Example
...
...
...

@ManagedBean
@RequestScoped
public class ContactListMB {
    //services
    private ContactListService contactListService;

    @PostConstruct
    public void postConstruct() {
        contactListService = JSFSpringUtils.getBean(ContactListService.class);
    } 
    
    ...
    ...
    ...
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น