News - tagged as "cdi2"

Weld 3.0.0.Alpha16

2016-4-28   release , cdi2   Martin Kouba

The next experimental Weld version has been released! See also the release details. Thanks to everyone involved in this release!

This release includes a lot of bugfixes and improvements (e.g. all the notable tasks implemented in the latest stable version: Weld 2.3.4.Final). However, the main goal of this release is to align with CDI API 2.0.Alpha4, and in particular to implement the current version of "metadata builders" API (CDI-558). So that everyone can play with the API, discover possibilities and find potential issues. Note that this release also introduces a non-standard experimental feature: Weld SE synthetic container lifecycle event observers. So it should be even easier to get started - no extension class is needed in Weld SE.

Metadata configurators - basic ideas

Note that we don’t use the term "builder" because there is no build() method in the API. Also note that the API is not intended to cover every possible case. Instead, we would like to help with common tasks. And if necessary, an extension developer can always use the original replacement methods for more complicated stuff.


  • an extension developer receives a configurator instance from a container lifecycle event

  • a configurator instance is always automatically processed at the end of the observer invocation

  • for bean discovery events (all events starting with Process):

    • configureX() methods return the same configurator instance (for the given observer method invocation)

    • the configurator is initialized/preconfigured with the component being processed, e.g. ProcessAnnotatedType.configureAnnotatedType() returns a configurator initialized with ProcessAnnotatedType.getAnnotatedType()

    • the result of the configurator will automatically replace the original component (e.g. AnnotatedType in case of ProcessAnnotatedType)

    • replacement methods (e.g. ProcessAnnotatedType.setAnnotatedType()) should not be used together with configurators (CDI-596)

  • for application lifecycle events (e.g. AfterBeanDiscovery):

    • addX() methods always return a new configurator instance

    • the configurator is always uninitialized/empty, but we should probably define some default values wherever it makes sense (e.g. Reception for observer methods)

    • the result of the configurator will be automatically added (e.g. Bean in case of AfterBeanDiscovery.addBean())

We have prepared some simple examples - see below. More advanced examples can be found in the TCK test cases. And as usual - feel free to add comments to this blog post. Any feedback is appreciated!

BeforeBeanDiscovery example

    class MyService {
        // This class is not placed in a bean archive
    class MyExtension implements Extension {
        void beforeBeanDiscovery(@Observes BeforeBeanDiscovery event) {
            // Add MyService to the set of discovered classes and replace @Singleton with @ApplicationScoped
            event.addAnnotatedType(MyService.class.getName(), MyService.class)

ProcessAnnotatedType example

class MyExtension implements Extension {
        void processAnnotatedType(@Observes @WithAnnotations({ Observes.class, ObservesAsync.class }) ProcessAnnotatedType<?> event) {
            // Add interceptor binding to all methods annotated with @Observes or @ObservesAsync
                    .forEach(methodConfigurator -> methodConfigurator.add(Monitored.Literal.INSTANCE))
        static boolean isObserver(AnnotatedMethod<?> annotatedMethod) {
            return annotatedMethod.isAnnotationPresent(Observes.class) || annotatedMethod.isAnnotationPresent(ObservesAsync.class);

ProcessBeanAttributes example

class MyExtension implements Extension {
        void processBeanAttributes(@Observes ProcessBeanAttributes<?> event) {
            // For all beans remove the IllegalBeanType from the set of bean types
            if (event.getBeanAttributes().getTypes().contains(IllegalBeanType.class)) {
                Set<Type> legalTypes = new HashSet(event.getBeanAttributes().getTypes());

AfterBeanDiscovery example

class MyExtension implements Extension {
        void afterBeanDiscovery(@Observes AfterBeanDiscovery event) {
            //  Add a new synthetic observer method - no need to use the fluent API
            ObserverMethodConfigurator<Foo> configurator = event.<Foo>addObserverMethod();
            configurator.notifyWith((foo) -> System.out.println("Foo observed: " + foo));
            // Add dependent bean - Integer between 0 and 999
                    .produceWith(() -> new java.util.Random().nextInt(1000))

WildFly Patch

As usual, a patch for WildFly is available. This time the target platform is WildFly 10.0.0.Final. If you’re not familiar with patching WildFly, check Markus’s tutorial.

Weld 3.0.0.Alpha15

2016-2-4   release , cdi2   Martin Kouba

Weld 3.0.0.Alpha15 the next experimental Weld version has been released. See also the release details.

The CompletionStage used to bind actions to the completion of the asynchronous delivery is now using org.jboss.weld.manager.api.ExecutorServices SPI as the default asynchronous execution facility. Previously, the ForkJoinPool#commonPool() (a default executor of the underlying CompletableFuture) was used. It’s an important change because the ForkJoinPool#commonPool() is not a good fit for Java EE. See also WELD-2073.

The ExperimentalAfterBeanDiscovery receives two more methods: interceptorBuilder() and addInterceptor(). An interceptor builder allows you to create an interceptor bean without the need to create an interceptor class. This might be handy for simple use cases:

class MyExtension {
      void afterBeanDiscovery(@Observes AfterBeanDiscovery event) {
        event.addInterceptor().intercept(InterceptionType.AROUND_INVOKE, (c) -> {
                long start = System.currentTimeMillis();
                try {
                    return c.proceed();
                } finally {
                    System.out.println("Time: " + System.currentTimeMillis() - start);

See also WELD-2008.

This release also contains some enhancements and bugfixes around proxies. E.g. better support for DeltaSpike partial beans (WELD-2084), better support for Camel CDI (WELD-2089) and better support for proxies with non public classes (WELD-2091). Furthermore, we are going to drop Jetty 7,8, 9.0, 9.1 and 9.2 support in Weld 3 (WELD-2032). Also the decorator validation was improved (WELD-2085, WELD-1811, WELD-2039). Last but not least, we have performed some SPI cleanup (WELD-2077, WELD-2079).

WildFly Patch

As usual, a patch for WildFly is available. This patch not only upgrades Weld within an existing WildFly instance but also upgrades CDI API to 2.0 EDR1. This time the target platform is WildFly 10.0.0.Final. If you’re not familiar with patching WildFly, check Markus’s tutorial.

Weld 3.0.0.Alpha14

2015-12-4   release , cdi2   Martin Kouba

Weld 3.0.0.Alpha14 the penultimate Weld version for this year has been released into the wild. It reflects some of the most recent changes in the CDI 2.0 specification, mostly related to asynchronous events. Moreover, this release also contains quite a lot of enhancements and bugfixes. See also the release details.

WildFly Patch

As usual, a patch for WildFly is available. This patch not only upgrades Weld within an existing WildFly instance but also upgrades CDI API to 2.0 EDR1. This time the target platform is WildFly 10.0.0.CR4. If you’re not familiar with patching WildFly, check Markus’s tutorial.

Weld 3.0.0.Alpha12 - CDI 2.0 EDR1 Reference Implementation!

2015-8-5   release , cdi2   Martin Kouba

Weld 3.0.0.Alpha12 has been released. Compared to previous alpha releases this is an important milestone - it’s a reference implementation of CDI 2.0 Early Draft (EDR1). You can read more about CDI 2.0 EDR1 on the official blog: CDI 2.0 Early Draft Review 1 released.

Bootstrapping a CDI container in Java SE

Starting a CDI container is now really that easy:

public static void main(String... args) {
        try(CDI<Object> cdi = CDI.getCDIProvider().initialize()) {
            ComputingService service =;

javax.enterprise.inject.spi.CDI now implements AutoCloseable and can therefore be used in a try-with-resources block.

Note that the specification of the bean discovery process in Java SE is not finished yet. Therefore, bean archives which don’t contain a beans.xml file are not supported. The main reason is that we don’t want to implement a feature which is being discussed and will likely undergo some important changes. Nevertheless, the feature will be implemented in one of the next alpha versions.

Weld SE bootstrap API

How does it compare to Weld SE bootstrap API? Weld has provided support for the Java SE environment for a long time. Recently, the class was turned into a powerful builder which allows to configure the Weld container before it is initialized.

Typical usage of the Weld SE API looks like this:

try (WeldContainer container = new Weld().initialize()) {
        ComputingService service =;

This looks very similar to CDI SE, right? However, there are several advanced feratures available:

  • automatic scanning can be disabled, classes or packages can be selected explicitly

    • WeldContainer container = new Weld().disableDiscovery().beanClasses(Foo.class, Bar.class).alternatives(Bar.class).interceptors(FooInterceptor.class).initialize();

  • WeldContainer allows to fire events easily

    • container.event().select(Bar.class).fire(new Bar());

  • Weld-specific configuration options can be specified using the builder

  • it is possible to start multiple independent Weld instances (specification does not require this)

See also Weld 3.0.0.Alpha8 announcement for more information.

Asynchronous Events

An experimental support of asynchronous events is implemented in Weld since 3.0.0.Alpha3. However, in this release the API was aligned with CDI 2.0 EDR1:

class OrderProcessor {
        @Inject Event<Order> orderEvent;
        public void process(Order order) {
            orderEvent.fireAsync(order).thenAccept((o)->System.out.println("Asynchronous processing finished: " + o.getId()));
        public void processingOrder(@Observes Order event) {
            // This observer is notified synchronously, before the fireAsync() method returns
        public void asyncProcessingOrder(@ObservesAsync Order event) {
            // This observer is notified asynchronously, in a different thread

There are few important things to notice:

  • the event was triggered with fireAsync()

  • the asynchronous observer is defined by @ObservesAsync

  • synchronous observers defined by @Observes are also notified!

To sum it up:

Event method @Observes notified @ObservesAsync notified


yes, in the same thread



yes, in the same thread

yes, in a different thread

Observers SPI Changes

javax.enterprise.inject.spi.ObserverMethod now extends javax.enterprise.inject.spi.Prioritized and overrides the ObserverMethod.getPriority() method which is used to determine the notification order in which the event observer methods are invoked. Prioritized interface is currently only used for observers. However, the Weld team is working on a prototype where Prioritized can be used to globally select/enable custom alternative beans, interceptors and decorators, see also WELD-2000.

Furthermore, ObserverMethod.isAsync() method was added to determine whether an observer method is asynchronous or not.

WildFly Patch

As usual, a patch for WildFly is available. This patch not only upgrades Weld within an existing WildFly instance but also upgrades CDI API to 2.0 EDR1. This time the target platform is WildFly 10.0.0.Alpha6. If you’re not familiar with patching WildFly, check Markus’s tutorial.

Weld 3.0.0.Alpha8

2015-4-21   release , cdi2   Jozef Hartinger

Weld 3.0.0.Alpha8 has been released. The main change is the enhanced API for using Weld in Java SE environment. In addition, this release comes with several weld-probe improvements.

Enhanced API for Weld SE

Weld has provided support for the Java SE environment for a long time with the weld-se module. The API provides an easy way for an application to initialize Weld and use it in a standalone mode. On initialization Weld SE scans the classpath for bean archives with the beans.xml file, similarly to how it’s done in the Java EE environment.

In this release we are extending the API further. This is partially inspired by the current discussion in the CDI expert group where a standardized CDI API for Java SE is being proposed as part of CDI-26.

The following code snippet shows the new API in action:

Weld builder = new Weld()
        .packages(Main.class, Utils.class)
        .property("", true);
    try (WeldContainer weld = builder.initialize()) {
        MyBean bean =;

There are several new things to notice:

  • the Weld class is used as a builder to configure Weld before it is initialized

  • automatic scanning can be disabled

  • instead of scanning, classes or packages can be selected explicitly. All classes in those packages will be managed by Weld

  • interceptors, decorators, extensions and Weld-specific configuration options can be specified using the builder

  • WeldContainer now implements AutoCloseable and can therefore be used in a try-with-resources block. At any time that execution gets outside of the code block, the Weld instance is shut down and all managed instances are safely destroyed.

It is also possible to start multiple independent Weld instances:

new Weld().disableDiscovery().containerId("one").beanClasses(MyBean.class).initialize();
    new Weld().disableDiscovery().containerId("two").beanClasses(OtherBean.class).initialize();
    MyBean bean = WeldContainer.instance("one").select(MyBean.class).get();

Here, two independent WeldContainer instances are initialized. Each of them is given a unique ID. The ID can subsequently be used to obtain a WeldContainer reference in a different place of the code. One possible use-case this enables is for a library or framework (e.g. a testing framework) to use an embedded instance of Weld internally for its own needs (dependency injection, events, extensibility). This instance would not interfere with the Weld instance used by the application.

Obviously, automatic classpath scanning can still be used as before:

try (WeldContainer weld = new Weld().enableDiscovery().initialize()) {
        MyBean bean =;


To play with the new API use the following dependency in you Maven project:


Aforementioned classes are from the package.

Weld Probe Enhancements

Since the last Alpha releases there were several enhancements to Weld Probe. If you are not familiar with Weld Probe, check this introductory blog post first.

A new feature of Probe is that, when the development mode is enabled, it now embeds a tiny information bar directly into the application’s HTML output. That makes it easy to navigate to Probe directly from the application anytime. Furthermore, if invocation tracking is enabled, the information bar helps navigate directly to the invocation tree related to the request that rendered the output.

Weld Probe information bar embedded in application’s HTML output

Additionally, the following Probe improvements were implemented:

  • tracked invocations are now grouped into a invocation tree instead of being tracked in isolation

  • a special type of edges is now used in the overview graph to represent a "declared by" relation (when a bean declares a producer method or field)

  • Instance<?> injection points are now treated specially - a resolved bean is show as injection point’s dependency

[ Experimental API documentation ] [ Release notes ] [ Distribution ] [ Patch for Wildfly (8.2, 9 Beta) ]

Weld 3.0.0.Alpha5

2015-2-25   release , cdi2   Jozef Hartinger

Weld 3.0.0.Alpha5, the latest release in the series of CDI 2.0 prototypes, has been released. The highlights of the release include new Bean builder API and many improvements to Weld Probe.

Bean Builder API

The common way for frameworks and libraries to expose their API to applications via CDI is by using producer methods. An alternative approach is a custom implementation of the javax.enterprise.inject.spi.Bean interface that is registered by a CDI portable extension. This latter approach gives the extension more control but is also less straightforward.

One of the goals of CDI 2.0 is to fill this gap and simplify extension development. This Weld release comes with a preview of the Bean builder API. The API is inspired by Bean builder API provided by DeltaSpike. In addition, Java 8 lambdas are used in the API to simplify the entire process even further.

Here’s an example of a simple extension that builds and registers a bean:

void register(@Observes ExperimentalAfterBeanDiscovery event) {
            .produceWith(() -> new java.util.Random().nextInt(1000));

That’s it! Likewise, it is easy to can define a bean with custom disposal logic using a lambda expression:

void register(@Observes ExperimentalAfterBeanDiscovery event) {
            .disposeWith(connection -> connection.close());

See the BeanBuilder Javadoc for more information.

Event monitoring with Probe

We introduced Probe in the previous blog post. This release adds event monitoring view to Probe. In this view both system and application events are displayed. The events can be filtered by type and qualifiers. It is also possible to track which observer methods a particular event was delivered to.

Weld Probe event monitoring

Further improvements

In addition, there were a couple of minor improvements to Probe, namely:

  • better filtering of invocation trees - Probe now searches the whole tree, not just the entry points

  • the context view now displays the conversation context

  • Probe is now more careful and does not try to bind interceptors to classes that are not proxyable

  • all the configuration options for Probe are now documented

The easiest way to get Probe to run locally is to patch WildFly with a Weld patch. If you’re not familiar with patching WildFly, check Markus’s tutorial.

Relaxed construction

CDI requires that beans that are normal-scoped, intercepted or decorated always define a no-argument constructor. This requirement applies even if the bean already defines an @Inject annotated constructor with parameters. This is purely a technical requirement implied by how Java allocates class instances.

Weld is however able to operate fine even if this requirement is not met. Weld uses special non-portable JVM APIs that allow it to allocate proxy instances without calling proxy’s constructor. This mode is non-portable and needs to be explicitly enabled using a configuration option.

This mode is not new but has been neglected in the past. For this release we added a bunch of tests for this mode, fixed a lot of bugs and enabled it by default in Weld-SE. Any feedback on this mode is appreciated.

Weld 3.0.0.Alpha4

2015-2-5   release , cdi2   Jozef Hartinger

Here we are again with the next Alpha release of Weld 3. This time there are no additional CDI 2.0 previews. Instead, this release contains multiple performance improvements, enables @Asynchronous calls to be implemented simply with CDI interceptors and most importantly, it comes with weld-probe.

Weld Probe

Why isn’t my field injected? Why isn’t my interceptor triggered? What extensions do third-party libraries register?

Have you ever found yourself asking a similar question? Making Weld developer-friendly and helpful in troubleshooting is our priority. Yet, similar problems still occur sometimes.

But we can do event better! In Alpha4 of Weld 3 we are introducing a new tool called Weld Probe. Probe is a built-in tool that provides a detailed view into internals of a CDI application. Weld Probe has a web UI and is provided out-of-the-box.

Probe makes it easy to inspect:

  • beans, their properties such as qualifiers, stereotypes and name

  • a graph of bean dependencies

  • observers and producers declared by beans

  • interceptors and decorators bound to a bean

  • extensions

  • information about current contextual instances

  • tracking of invocations and invocation trees

Plus more addons are planned in future.

Weld Probe Screenshot

To try probe all that needs to be done is to upgrade to Alpha4, enable the development mode and point your browser to the URL of your CDI application plus /weld-probe suffix.

For more thorough overview of what Probe provides see Martin’s blog post or the reference documentation.

Bear in mind that Probe is still work in progress and that this early preview may have defects here and there.

Implementing @Asynchronous using CDI interceptor

It is possible to implement a substitute for EJB @Asynchronous method calls using CDI interceptors. Arjan Tijms recently blogged about his solution A similar one can be found in Weld’s testsuite. Long story short: This would not work smoothly until now because of a limitation in Weld. This limitation is now gone in Alpha4.


This release integrates various runtime performance improvements mainly around bean instance construction, producer and observer method invocation.


Weld 3.0.0.Alpha5 is planned in 3 weeks time from now, with some more CDI 2.0 previews. We are going to continue releasing Alpha versions of Weld 3.0 roughly every 3 weeks until the early draft of CDI 2.0, which should happen sometime in March. At that point, we’ll move to Beta releases.

In the meantime, we’d like to hear your feedback on Probe or on Weld 3.0 Alpha releases in general. Feel free to use our forums or #weld-dev on freenode

An update on Weld 3

2014-12-10   cdi2   Jozef Hartinger

Today we are releasing the third Alpha release of Weld 3. These Alpha releases serve as prototypes of changes currently being discussed by the CDI expert group for the upcoming CDI 2.0.

The Alpha releases are not suitable for production use as the new API and functionality are still subject to change. We are releasing them to allow the community to test-drive the changes early in the development cycle. We want to shorten the feedback loop and identify possible glitches as soon as possible.

Let’s just quickly review what has been available since Alpha1:

  • declarative ordering of observer methods using @Priority

  • ability for an extension to veto and modify an observer method

  • support for Java 8 repeatable annotations as qualifiers and interceptor bindings

  • enhanced AnnotatedType API

For more details and examples of these features see my previous blog post.

On top of this, we’re now adding the following new features and enhancements:

  • asynchronous events

  • simplified configuration of Weld-specific properties

  • Guava is no longer used internally

Asynchronous events

Since its first version CDI has provided events as a facility for component interaction. Events enable loose coupling while preserving type safety. So far, CDI has supported synchronous delivery of events - the calling thread blocks until invocations of all associated observer methods complete. An alternative to this are transactional observer methods which are called asynchronously at the end of a transaction.

For the upcoming CDI 2.0 specification one of the hot topics is enhancement of the events facility. The expert group is considering adding fully asynchronous event dispatching mechanism.

A working prototype of this is available in Weld 3.0.0.Alpha3. The current proposal adds a method called fireAsync to the existing Event interface.

    private ExperimentalEvent<Configuration> event;
    event.fireAsync(new Configuration());

The call to event.fireAsync() returns immediately. The event is delivered to corresponding observers in a dedicated thread pool that can be configured.

What about thread-safety?

There are two common usage pattens for events. In the first one an immutable event object is used. An alternative is to use mutable events. A mutable event allows observers to participate on the result which is later used by the component that fired the event. An example of this would be the ProcessAnnotatedType<T> event used by CDI extensions. When events are fired synchronously, both approaches work fine but how does this work when we switch to async?

Nothing changes actually. No matter if the event object is immutable or not, you do not have to worry about thread-safety of the event object. The current implementation comes with the guarantee that event object is safely published which means that an observer method observes the event in the state in which:

  • it was left by an observer executing before the given observer, or

  • the initial state of the event if the given observer is the first one

Furthermore, the state is consistent throughout the execution of an observer method which means that we guarantee safe publication and prevent races for you. The only thing that should be avoided is modifying the state of the event object outside of an observer method. This behavior matches the option in the current spec proposal.

In addition, if observer methods are ordered (another new feature proposed for CDI 2.0) we preserve the ordering (as in such situation the observers are ordered for a reason!) and invoke observers in the given order.

Last but not least, if an observer is transactional, we again preserve this and invoke the observer method in the corresponding transaction phase.

How do I know when event delivery finishes and what about exceptions?

In the current prototype we’re reusing the CompletionStage API, introduced in Java 8, which allows actions (callbacks) to be bound to the completion of the asynchronous delivery process. This is what it looks like:

event.fireAsync(new Configuration()).thenAccept(config -> master.compute(config));

This piece of code starts with asynchronously firing a mutable configuration object allowing loosely-coupled observers to alter the configuration of a computation. Once all observers finish, computation is initiated based on the resulting configuration.

If an exception occurs this can be dealt with also, either by falling back to a default value

event.fireAsync(new Configuration())
        .exceptionally(throwable -> DEFAULT_CONFIGURATION)
        .thenAccept((config) -> master.compute(config));

or by executing arbitrary code:

event.fireAsync(new Configuration()).whenComplete((config, throwable) -> {
        if (throwable != null) {
            System.err.println("Oops. Failed because of " + throwable.getMessage());
        } else {

CompletionStage allows much more. If you are unfamiliar with the API see the Javadoc page for more information.

How do I try this myself?

It’s easy and multiple options are available. First of them is to use Weld in a standalone application.

  1. Create a new Java SE application.

  2. Add dependency on Weld

  3. Create an empty beans.xml file, e.g.

    mkdir src/main/resources/META-INF
        touch src/main/resources/META-INF/beans.xml
  4. Launch Weld and fire an event asynchronously

    public static void main(String[] args) {
            WeldContainer weld = new Weld().initialize();
            Event<String> evnt = weld.event().select(String.class);
            ExperimentalEvent<String> event = (ExperimentalEvent<String>) evnt;


Alternatively, a patch is available for WildFly that upgrades Weld within an existing WildFly instance. See the download page for more details.

Note that these new prototyped APIs are not part of the CDI API yet. Instead, they are currently located in Weld API in a package named org.jboss.weld.experimental

All these altered APIs have the Experimental prefix (that’s why we are using ExperimentalEvent in the examples)

We would appreciate your feedback! Feel free to use Weld forums or the cdi-dev mailing list for this purpose.

What’s next?

We are going to continue releasing early prototypes of features currently proposed for CDI 2.0. The plan is to release a new Alpha version every 3 weeks. There are several areas we want to focus on:

  • simplifying how extensions register beans and observers

  • monitoring and debugging of CDI applications

  • experimenting with full interception (intercepting even calls within a given component)

  • splitting the codebase into a “light” and “full” version (to support proposed CDI light version)

  • bootstrap API for SE environment