(Mainly for integration tests) I have some beans defined which I want to decide programmatically which to add to the container. After some fiddling around I found a way to do it, by annoating the relevant beans as @Alternative and then having a CDI extension that observes the AfterBeanDiscovery event and then adds the beans I want to have present in the container. This is the relevant code. It is in Groovy, but I think you get the meaning, otherwise I'll rewrite it for you in Java. beans is a Collection<Class<?>> that is set in the constructor.
private void addBeans(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) {
beans
.collect(beanManager.&createAnnotatedType)
.each { annotatedBeanType ->
afterBeanDiscovery
.addBean()
.read(annotatedBeanType)
.alternative(false)
}
}
This code seems to work fine and do exactly what I want and need. But I found one downside to it. If the relevant beans contain observer methods, those are not registered in the container and thus do not get any events dispatched. If this is working as designed, then sorry for again reporting a non-issue. |