给定
public class BeanContainer {
@Produces
Bean bean = new Bean();
}
及其替代方案:
@Alternative
public class BeanContainerAlt extends BeanContainer {
@Produces
int producerInt = 10;
}
比恩在哪里
public class Bean {
boolean didPostConstruct = false;
@PostConstruct
public void postConstruct() {
didPostConstruct = true;
}
}
注入 MainClass:
public class MainClass {
@Inject
Bean bean;
@Inject
Integer producedInt;
}
然后:
Weld weld = new Weld()
.disableDiscovery()
.addBeanClass(MainClass.class)
.addBeanClass(BeanContainer.class)
.addBeanClass(BeanContainerAlt.class)
.alternatives(BeanContainerAlt.class);
WeldContainer container = weld.initialize();
final MainClass mainClass = container.select(MainClass.class).get();
assertFalse(mainClass.bean.didPostConstruct);
assertEquals(10, (long)mainClass.producedInt);
BeanContainer containerObject = container.select(BeanContainer.class).get();
assertEquals(BeanContainerAlt.class, containerObject.getClass());
没有错误。我原以为必须使用 addBeanClass 添加Bean.class才能满足MainClass中的注入。解释是BeanContainerAlt的超类,其Producers应该是无效的,产生了Bean-Object。这种行为是有意的还是根据规范(我没有找到),它可能在焊接文档中定义吗?
源代码可以在 examplesrc中找到
mvn clean install -Dtest=ReproProducersInSuperclasses
在那个项目中应该让它运行