Java SE support
The Java SE support in weld is now standardized, it is useful when you want to get CDI support out of Java EE application servers.Given a simple CDI bean.
@Named
@ApplicationScoped
public class Greeter {
public void say(String name) {
System.out.println("Hi, " + name);
}
}
SeContainer
like this. SeContainerInitializer initializer = SeContainerInitializer.newInstance();
try (SeContainer container = initializer.initialize()) {
assertTrue(container.isRunning());
Set<Bean<?>> greeters = container.getBeanManager().getBeans("greeter");
assertTrue(greeters.size() == 1);
}
try-resources
statement, SeContainer
is a AutoClosable
and can be closed automaticially at the end.To bootstrap CDI container for Java SE, you have to add the following dependencies in project.
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-shaded</artifactId>
<version>3.0.0.Final</version>
</dependency>
Weld weld = new Weld();
try (WeldContainer container = weld.initialize()) {
Greeter greeter = container.select(Greeter.class).get();
assertTrue(greeter != null);
}
@Test(expected = UnsatisfiedResolutionException.class)
public void bootWeldSeContainer() {
Extension testExtension = ContainerLifecycleObserver.extensionBuilder()
.add(afterBeanDiscovery((e) -> System.out.println("Bean discovery completed!")))
.add(processAnnotatedType().notify((e) -> {
if (e.getAnnotatedType().getJavaClass().getName().startsWith("com.hantsylab")) {
e.veto();
}
}))
.build();
try (WeldContainer container = new Weld().addExtension(testExtension).initialize()) {
Greeter greeter = container.select(Greeter.class).get();
//assertTrue(greeter == null);
}
}
Greeter
bean in processAnnotatedType
phase, the later bean select operation will cause an exception UnsatisfiedResolutionException
thrown.Grab the source codes from my github account, and have a try.
评论