尽管 Bozho 提供的解决方案可以工作,但我不想将代理对象引入当前未使用它们的应用程序中。我的解决方案不太理想,但它完成了工作。
我将瞬态字段留在原处:
transient private ApplicationData _applicationData;
我还保留了 setter,以便 JSF 可以SessionData
在第一次创建对象时初始设置引用:
public void setApplicationData(ApplicationData applicationData) {
_applicationData = applicationData;
}
我所做的更改是在 getter 方法中。对象中的方法SessionData
现在需要停止直接访问该_applicationData
字段,而是通过 getter 获取引用。getter 将首先检查空引用。如果为 null,则通过FacesContext
. 这里的限制FacesContext
是 仅在请求的生命周期内可用。
/**
* Get a reference to the ApplicationData object
* @return ApplicationData
* @throws IllegalStateException May be thrown if this method is called
* outside of a request and the ApplicationData object needs to be
* obtained via the FacesContext
*/
private ApplicationData getApplicationData() {
if (_applicationData == null) {
_applicationData = JSFUtilities.getManagedBean(
"applicationData", // name of managed bean
ApplicationData.class);
if (_applicationData == null) {
throw new IllegalStateException(
"Cannot get reference to ApplicationData object");
}
}
return _applicationData;
}
如果有人关心,这是我的getManagedBean()
方法的代码:
/**
* <p>Retrieve a JSF managed bean instance by name. If the bean has
* never been accessed before then it will likely be instantiated by
* the JSF framework during the execution of this method.</p>
*
* @param managedBeanKey String containing the name of the managed bean
* @param clazz Class object that corresponds to the managed bean type
* @return T
* @throws IllegalArgumentException Thrown when the supplied key does
* not resolve to any managed bean or when a managed bean is found but
* the object is not of type T
*/
public static <T> T getManagedBean(String managedBeanKey, Class<T> clazz)
throws IllegalArgumentException {
Validate.notNull(managedBeanKey);
Validate.isTrue(!managedBeanKey.isEmpty());
Validate.notNull(clazz);
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext == null) {
return null;
}
Validate.notNull(facesContext.getApplication());
ELResolver resolver = facesContext.getApplication().getELResolver();
Validate.notNull(resolver);
ELContext elContext = facesContext.getELContext();
Validate.notNull(elContext);
Object managedBean = resolver.getValue(
elContext, null, managedBeanKey);
if (!elContext.isPropertyResolved()) {
throw new IllegalArgumentException(
"No managed bean found for key: " + managedBeanKey);
}
if (managedBean == null) {
return null;
} else {
if (clazz.isInstance(managedBean)) {
return clazz.cast(managedBean);
} else {
throw new IllegalArgumentException(
"Managed bean is not of type [" + clazz.getName() +
"] | Actual type is: [" + managedBean.getClass().getName()+
"]");
}
}
}
并且不要接听我的验证电话。开发完成后我会把它们拿出来!:)