簡體   English   中英

FacesConverter注入變通方法 - 構造函數替代方案

[英]FacesConverter Inject workaround - constructor alternative

這與已知的JSF FacesConverter問題的解決方法無關,因為它不是CDI的合格@Inject目標。 我將CDI Injection的解決方法跟進了FacesConverter 但是,在我的FacesConverter中,我一直在利用將對象的Class傳遞給構造函數的功能。

javadoc - “如果一個轉換器有一個帶有Class實例的單個參數構造函數,並且在轉換器實例化時知道要轉換的數據的類,則必須使用此構造函數來實例化轉換器而不是零參數版本“。 這與“正常范圍”bean的CDI要求直接沖突,其中no-arg或@Inject帶注釋的構造函數是允許的。

總而言之,我想使用一個可以進行CDI注入的轉換器,並且可以訪問在運行時轉換的對象的類。

我使用Weld 2.0.4在Glassfish 4上使用Mojarra 2.2.4。

對於那些可能對這個替代方案感興趣的人,我能夠在構造函數中通過BeanManager將編程注釋替換為Inject注釋。 精簡代碼如下。 我沒有經過性能測試,並懷疑這可能是一個缺點。 如果時間允許,我將與Omnifaces解決方案進行比較。

編輯:BeanManager查找的成本最低。 構造函數平均<1ms。

@FacesConverter(forClass = AbstractEntity.class)
public class EntityConverter implements Converter {

    private LocationService locationService;
    private Class entityClass;

    //Special parameterized constructor for @FacesConverter described in the original question
    public EntityConverter(Class entityClass) throws NamingException {
            this.entityClass = entityClass;
            this.locationService = loadManagedBean(LocationService.class, "locationService");
        }

    //Generic lookup method for @Named managed beans
    protected <T> T loadManagedBean(Class<T> clazz, String beanName) throws NamingException {
            InitialContext initialContext = new InitialContext();
            BeanManager bm = (BeanManager) initialContext.lookup("java:comp/BeanManager");

            Bean<T> bean = (Bean<T>) bm.getBeans(beanName).iterator().next();
            CreationalContext<T> cc = bm.createCreationalContext(bean);
            T beanInstance = (T) bm.getReference(bean, clazz, cc);
            return beanInstance;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM