org.infinispan.cdi.common.util.ContextualReference Maven / Gradle / Ivy
package org.infinispan.cdi.common.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import jakarta.enterprise.context.spi.CreationalContext;
import jakarta.enterprise.inject.spi.Bean;
import jakarta.enterprise.inject.spi.BeanManager;
/**
* Represents a non-contextual instance
*/
public class ContextualReference {
private final Bean bean;
private T instance;
private boolean disposed = false;
public ContextualReference(BeanManager beanManager, Type beantype, Annotation... qualifiers) {
this.bean = (Bean) beanManager.resolve(beanManager.getBeans(beantype, qualifiers));
}
/**
* Get the instance
*/
public T get() {
return instance;
}
/**
* Create the instance
*/
public ContextualReference create(CreationalContext ctx) {
if (this.instance != null) {
throw new IllegalStateException("Trying to call create() on already constructed instance");
}
if (disposed) {
throw new IllegalStateException("Trying to call create() on an already disposed instance");
}
this.instance = bean.create(ctx);
return this;
}
/**
* destroy the bean
*/
public ContextualReference destroy(CreationalContext ctx) {
if (this.instance == null) {
throw new IllegalStateException("Trying to call destroy() before create() was called");
}
if (disposed) {
throw new IllegalStateException("Trying to call destroy() on already disposed instance");
}
this.disposed = true;
bean.destroy(instance, ctx);
return this;
}
}