以下解决方案受到Adam Warski 的启发,另请参阅BeanManager Javadoc
首先,我需要两个实用方法:
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class Utils {
public static BeanManager getBeanManager() {
try {
InitialContext initialContext = new InitialContext();
return (BeanManager) initialContext.lookup("java:comp/BeanManager");
} catch (NamingException e) {
throw new RuntimeException("Failed to retrieve BeanManager!", e);
}
}
public static <T> T getBean(Class<T> c) {
T result = null;
BeanManager bm = getBeanManager();
Set<Bean<?>> beans = bm.getBeans(c);
if (! beans.isEmpty()) {
Bean<?> bean = beans.iterator().next();
result = c.cast(bm.getReference(bean, c, bm.createCreationalContext(bean)));
}
return result;
}
}
AnItem
然后必须像这样更改类:
@XmlRootElement(name = "item")
class AnItem {
MyFactory myFactory = Utils.getBean(MyFactory.class);
...
}