对于那些可能对这种替代方案感兴趣的人,我可以通过构造函数中的 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;
}
}