I am using Weld SE in a junit test. It seems it does not inject an inner field of a CDI bean. I am using the maven artifcat weld-se-shaded (4.0.2-Final)
import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class XService {
@Override
public String toString() {
return "hi from XService";
}
}
// ---
import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class YService {
@Override
public String toString() {
return "hi from YService";
}
}
// ---
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
@ApplicationScoped
public class ZService {
@Inject
public YService yService;
@Override
public String toString() {
return "hi from ZService";
}
}
// ---
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class WeldTest {
private WeldContainer container;
@Before
public void startContainer() {
Weld weld = new Weld();
weld.disableDiscovery();
weld.addBeanClasses(XService.class, YService.class, ZService.class);
container = weld.initialize();
}
@After
public void stopContainer() {
container.shutdown();
}
@Test
public void shouldCreateXServiceInstance() {
// ok
XService xService = container.select(XService.class).get();
assertThat(xService.toString()).isEqualTo("hi from XService");
}
@Test
public void shouldCreateYServiceInstance() {
// ok
YService yService = container.select(YService.class).get();
assertThat(yService.toString()).isEqualTo("hi from YService");
}
@Test
public void shouldInjectYServiceInZService() {
// fails
ZService zService = container.select(ZService.class).get();
assertThat(zService.toString()).isEqualTo("hi from ZService");
// yService is null, assertion fails
assertThat(zService.yService).isNotNull();
}
}
There is no exception, the field is just null. Instead of field injection I tried constructor injection:
@ApplicationScoped
public class ZService {
public YService yService;
@Inject
public ZService(YService yService) {
this.yService = yService;
}
@Override
public String toString() {
return "hi from ZService";
}
}
In that case I get an exception message: org.jboss.weld.exceptions.UnsatisfiedResolutionException: WELD-001334: Unsatisfied dependencies for type ZService with qualifiers
Seems that Weld 4 only considers jakarta.*
imports. If I change javax.*
imports to jakarta.*
the example works. It also works if I am downgrading to Weld 3 with javax.*
imports.