Skip navigation

There is no doubt that unit/component testing is essential for most of the applications. Sometimes the component under the test needs to communicate with other components. This is where we usually reach for mocking frameworks. And if it's not sufficient (or too complicated) there are still integration tests. Integration tests are usually more time and resource-consuming though. And for CDI components mocks might very oftten become too complex. Not to mention the services provided by the container (interceptors, decorators, events, programmatic lookup, etc.) are hard to mock (if at all). That's the reason why Arquillian has an embedded Weld container. Recently, the first beta version (beta but stable and ready to use) of Weld JUnit extensions was released. Well, it's just another tool for testing CDI components. So how does it differ from other tools such as Arquillian, DeltaSpike Test Control and CDI-Unit? Well, it's really simple, easy to use, fast and it leverages the powerful Weld SE Bootstrap API.


Get Started

Just add one dependency to your pom.xml:




NOTE: At the time I wrote this article the artifact was only available in JBoss Maven repository. However, it should reach the Maven Central sooner or later.


And then add WeldInitiator test rule to your test:


import static org.junit.Assert.assertEquals;
import org.junit.Rule;
import org.junit.Test;

public class SimpleTest {

    public WeldInitiator weld = WeldInitiator.of(Foo.class);

    public void testFoo() {
        // Note that Weld container is started automatically
        // WeldInitiator can be used to perform programmatic lookup of beans
        // WeldInitiator can be used to fire a CDI event
        weld.event().select(Baz.class).fire(new Baz());



org.jboss.weld.junit.WeldInitiator is a test rule (JUnit 4.9+) which starts/stops a Weld container per test method execution. The container is configured through the Weld SE Bootstrap API, i.e. a provided instance. A convenient static method WeldInitiator.of(Class<?>...) is also provided - in this case, the container is optimized for testing purposes (with automatic discovery and concurrent deployment disabled) and only the given bean classes are considered. WeldInitiator also implements javax.enterprise.inject.Instance and therefore might be used to perform programmatic lookup of bean instances. It's also possible to use the convenient static method WeldInitiator.ofTestPackage() - the container is optimized for testing purposes and all the classes from the test class package are added. Sometimes, the programmatic lookup can imply unnecessary overhead, e.g. an annotation literal must be used for parameterized types and qualifiers with members. WeldInitiator.inject(Object) instructs the rule to inject the given non-contextual instance once the container is started, i.e. during each test method execution:


public class InjectTest {

    public WeldInitiator weld = WeldInitiator.of(Foo.class).inject(this);

    // Gets injected by WeldInitiator when testFoo() is about to be run
    Foo foo;

    public void testFoo() {
        assertEquals(42, foo.getValue());



And that's basically all. The Weld SE Bootstrap API is really powerful and allows to minimize the set of classes to be processed by the CDI container. As a result, the tests are fast and lightweight!

Ozark is the reference implementation of MVC 1.0 (JSR 371) and will be part of Java EE 8. This post is not about MVC features. It contains a few tips on how to try out Ozark on WildFly 10. The problem is Ozark currently depends on Jersey JAX-RS implementation. And so if you want to test it on a EE container other than GlassFish4 (and possibly others which bundle Jersey) you'll run into troubles. The good news is it's quite easy to add some additional configuration and run your MVC experiments on WildFly 10. Three additional steps are required:

  1. Bundle some Jersey artifacts
  2. Exclude JAX-RS subsystem (powered by RESTEasy)
  3. Suppress implicit bean archives without beans.xml - WildFly must ignore bundled hk2 libraries using JSR-330 @Inject


1. Bundle Jersey artifacts


We will need to add:

  • org.glassfish.jersey.containers:jersey-container-servlet
  • org.glassfish.jersey.ext.cdi:jersey-cdi1x
  • org.glassfish.jersey.ext:jersey-bean-validation (and also exclude hibernate-validator for this dependency)

See also the wildfly profile in


2. Exclude JAX-RS subsystem


Let's exclude the jaxrs subsystem by means of jboss-deployment-structure.xml descriptor:

<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.2">
            <subsystem name="jaxrs" />

See also


3. Suppress implicit bean archives without beans.xml


You could either supress implicit bean archives globally or per-deployment with jboss-all.xml descriptor in WEB-INF:

<jboss xmlns="urn:jboss:1.0">
    <weld xmlns="urn:jboss:weld:1.0" require-bean-descriptor="true"/>

See also


After this setup the MVC application should start working. Note that it's no proper integration but a simple workaround to allow you to test MVC RI on WildFly 10.

Dagger 2 is a popular dependency injection solution for Android and Java. It's designed primarily for restricted environments with limited resources. And it's also important that it's built on javax.inject annotations (JSR 330). If we dive into Dagger 2 internals we find out that all the important stuff is done at compile time. Annotation processors are responsible for lookup of bindings, validation of injection points, and finally generating the source code of factories responsible for instance creation. This approach brings advantages (for instance easier debugging and tiny runtime) and also limitations (no dynamism at runtime, injected fields cannot be private as no reflection is used, etc.).


Now the question is whether it would be possible to run Dagger 2 code in a CDI container? Sounds like a silly question, right? It should be feasible from the technical point of view but why would we need this? Well, imagine a useful library written in Dagger 2 which we would like to reuse in a CDI application. Or theoretically, we could start with Dagger 2 and when the application grows we need more advanced features (events, interceptors, etc.). We could either rewrite the code or emulate Dagger 2 behaviour and don't touch the code at all.


So how do we emulate Dagger 2 in a CDI container? There is a simple emulator prototype prepared.  Actually, there are only two classes. An extension which turns @Provides methods into producer methods and also restricts the set of bean types of each "emulated" bean (in Dagger 2 a binding, represented by a @Provides method or a class with an injectable constructor, can only have one type and one qualifier). And LazyAdaptor bean which is used for all injection points with dagger.Lazy (lazily-computed values) as a requested type. That's all. Injection points should not require any modifications. @Singleton scope is also supported in CDI. Note that unless a normal scope or interceptors are used we work with ordinary instances, i.e. no internal container constructs (e.g. client proxies) are used. Of course, this prototype is definitely not feature complete but it should work for simple use cases.


Checkout the repository and run mvn clean test. You should see the same output as for the Dagger's coffee example. The test is using the same test classes (CoffeeMaker, Thermosiphon, ...). Of course, the bootstrap code is different (we're using Weld SE).


Conclusion? It seems that it's quite straightforward to include "common" Dagger 2 code into an existing CDI application.

This feature has been implemented in the master branch for a while (Weld 3 alpha releases), but now it has been backported into the 2.2 branch and 2.2.10.Final is the first stable version of Weld with this simplified and unified configuration.


The Problem

Up to now, the configuration of Weld was a little bit difficult to use. There are several configurable components, each one was using a specific source of configuration (system property, marker file, properties file, etc.). The idea of WELD-1791 was to unify the configuration and still remain backward compatible if possible.


The Solution

First, every configurable option has a configuration key associated. There is a single place where all configuration keys are defined - see the org.jboss.weld.config.ConfigurationKey javadoc or 19.1. Weld configuration. Each configuration property (e.g. value for a configuration key) can be specified:

  1. in a properties file named (highest priority),
  2. as a system property,
  3. by a bootstrap configuration provided by an integrator (lowest priority).

If a configuration key is set in multiple sources (e.g. as a system property and in a properties file), the value from the source with higher priority is taken, other values are ignored. Unsupported configuration keys are also ignored. On the other hand, if an invalid configuration property value is set (e.g. the key expects an integer and recieves a string), the container automatically detects the problem and treats it as a deployment problem.



Say we want to disable the concurrent deployment, so that Weld loads and deploys beans sequentially (19.1.2. Concurrent deployment configuration). At the same time, we'd like to enable the relaxed construction (feature previously called "unsafe proxies"; 19.1.1. Relaxed construction). And finally, we would also like to dump the generated bytecode of client proxies and enhanced subclasses (19.1.6. Debugging generated bytecode).



What do we need to do in Weld before 2.2.10?

  1. Concurrent deployment - create a properties file and set concurrentDeployment key to false (or use integrator API)
  2. Relaxed construction - create a marker file META-INF/org.jboss.weld.enableUnsafeProxies
  3. Dump generated bytecode - set system property org.jboss.weld.proxy.dump to the desired path



The simplest solution would be to create a file named and place it on the classpath:


Of course, we could also use system properties or integrator API for all or some of the keys.



Unfortunately, there are always exceptions. First, for org.jboss.weld.xml.disableValidating key it's only possible to use system properties. However, this key is rather obscure and will not be used very often. Also web-specific settings are not part of the "core" configuration (e.g. 19.3. Mapping CDI contexts to HTTP requests).

Not only beginners sometimes struggle with the complexity of CDI. Simple cases are just simple but when it comes to more advanced topics one can easily become frustrated. Luckily some of the problems are solved by IDEs like JBoss Developer Studio. However, there are questions the static analysis simply can't answer.


Introducing the Probe

Weld 3.0.0.Alpha4 has a new feature - the development mode. When enabled, certain built-in development tools are available. The first tool which could facilitate the development of CDI applications is Weld Probe. It allows developers to inspect the application components at runtime. What exactly is it good for? If you ever asked a question similar to the following ones, it's the right tool for you:


  • What bean archives are there in my app?
  • How many extensions do affect my app?
  • What's the final set of beans in my app?
  • What are the real dependencies of my bean?
  • What beans are involved in a particular bean invocation?
  • In which bean archive is this interceptor/decorator enabled?


No Replacement For Debugger


Note that the point is not to replace tools such as debugger or profiler. It's more about understanding the application.


Get Started


The Probe consists of the REST API and the default (single-page application) client. Therefore it's only available in a web application. Right now, the integration is provided for WildFly (unofficial patch), Tomcat and Jetty (Weld Servlet). To enable the development mode just set the servlet initialization parameter org.jboss.weld.development to true:


<web-app version="3.1" xmlns=""




Once the development mode is enabled the Probe is automatically activated. The default client is available at path /weld-probe inside your web application, e.g. http://localhost:8080/weld-numberguess/weld-probe.


Default Client


Let's go through the default client and desribe the basic functionality available.



Bean Archives


This view shows all the bean archives in your application. The accessibility graph might be useful for complicated deployments. Note that additional bean archives (synthetic bean archives created for beans and extensions which do not belong to any regular bean archive) are hidden by default.



Weld Configuration


Look through the Weld configuration properties and their final values (see also Weld Configuration).




This view shows all the beans Weld is aware of. Note that  built-in beans and Java EE integration stuff  (e.g. for JSR 352: Batch Applications for the Java Platform) is shown as well. However, you can use various filters to find the beans you're interested in. The bean detail shows all important attributes, declared observers and producers, declaring bean for producers, and also dependencies and dependents.





Observer Methods


Discover all the registered observer methods, even those declared on extensions.






Do you remember the The Seam Debug Page? The purpose of this view is very similar - to inspect the bean instances in application and session contexts. There is a plan to support the Conversation context as well.



Invocation Trees


Sometimes it's useful to know what happens if a certain bean instance is called. The invocation tree shows all invocations within the given entry point. Where the entry point is the first business method invocation captured by the monitor in a certain thread. There is a plan to group invocations involved in a particular HTTP request.




Future and Plans


Weld Probe is still work in progress and we're working on new features, e.g. Fired Events log. Moreover, we're also considering whether it's worth backporting into Weld 2.2.x.


A slightly modified numberguess example with the development mode enabled is available at:  And the default client:


Give it a try and let us know. There is a "Development Tools (Probe)" JIRA component to track down probe-related issues. Your feedback is highly appreciated!

The target platform for CDI (JSR-346) is Java EE. However, Weld also supports Tomcat and Jetty servlet containers for a long time (even if the level of support is limited). Up to now, Weld was using the "flat deployment structure", i.e. all bean classes shared the same bean archive and all beans.xml descriptors are automatically merged into one. Thus alternatives, interceptors and decorators selected/enabled for a bean archive were enabled for an application. Of course, this is not correct per the spec. Moreover, CDI 1.1 introduced new types of bean discovery for implicit bean archives - bean-discovery-mode of annotated and none (see also Section 15.6, “Packaging and deployment” and Bean archives in CDI 1.1). Weld Servlet did not support this either and so all classes were always discovered.

Since version 2.2.5.Final, the bean archive isolation is enabled by default. So the only way to select/enable alternatives, interceptors and decorators for an application is to use @javax.annotation.Priority. Also implicit bean archives with bean-discovery-mode of annotated and none are handled correctly. As a bonus, Weld Servlet supports the use of Jandex bytecode scanning library to speed up the scanning process - simply put the jandex.jar on the classpath.

We are aware that the bean isolation could break some old applications. Therefore, the default behaviour can be changed (enforcing the use of the "flat deployment structure") by setting the servlet initialization parameter org.jboss.weld.environment.servlet.archive.isolation to false:


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns=""



Note that there is no such option to disable the implicit bean archive support.

As is well known, the class loading in WildFly is modular. A module may declare dependencies on other modules and these dependencies define the visibility rules. Moreover, a deployment is also a module (actually an EAR deployment usually consists of several modules). The core principles are explained in the documentation. Of course there is a way to add some dependencies automatically to the deployment so that developers are not required to declare these explicitly (Java EE APIs and implementations, logging providers, etc.) or even bundle into an archive. So every time an application is deployed, the responsible components from all the active subsystems are invoked for each application module. The result is a set of implicit module dependencies.


Note that a dependency does not have to be "active", i.e. the underlying technology need not be initialized (if a trigger condition is not met). However, from Weld point of view, all implicit module dependencies may have some impact on the deployment processing. To be more specific - there are subsystems/modules (JSF, JAX-RS, Batch, ...) which provide some kind of CDI integration. Typically such modules contain CDI portable extensions which observe container lifecycle events, provide own beans, register custom contexts, etc. Weld is processing all available portable extensions no matter if the module is "active" or not. The module itself may also be a CDI bean archive - in this case Weld automatically performs the bean discovery (discovers managed beans, producer methods, etc.).


The processing of portable extensions and bean archives brings additional overhead during deployment processing. Most likely the overhead won't be significant. Still it's possible to save a little bit of memory and time. Moreover it could be easier to analyze the Weld log debug output. Simply put, you can exclude unnecessary subsystems/dependencies. Basically there are two options. You can remove the extension which represents the subsystem from the server configuration (e.g. standalone.xml). However, this change will of course affect all the applications deployed. The other (more fine-grained) way is to use jboss-deployment-structure.xml (a JBoss-specific deployment descriptor) and exclude subsystems/dependencies per deployment only:


<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.2">
        <!-- Exclude unnecessary subsystems -->
            <subsystem name="jsf" />
            <subsystem name="batch" />
            <subsystem name="jaxrs" />


See also jboss-deployment-structure.xml example. Keep in mind that this configuration affects container functionality and you should use it with caution.

Martin Kouba

Bean archives in CDI 1.1

Posted by Martin Kouba Sep 20, 2013

Unlike CDI 1.0, the CDI 1.1 specification defines two types of bean archives: explicit and implicit. The first one is de facto the good old CDI 1.0 bean archive where all types in the archive are considered, i.e. the type metadata are inspected, the container must determine whether it is a bean, validate it, etc. If you place an empty beans.xml or CDI 1.0-specific  beans.xml you'll end up with an explicit bean archive. If you want to follow the new XSD for CDI 1.1, the bean discovery mode must be set to all:



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="" version="1.1" bean-discovery-mode="all">


The other type - implicit bean archive - is much more interesting and to be honest it also brings one compatibility issue. First let's look at the differences. The specification clearly states that an implicit archive contains one or more bean classes with a bean defining annotation, or one or more session beans. So that it doesn't have to contain a beans.xml file. However it may contain a  beans.xml file with the bean-discovery-mode of annotated.


For implicit bean archive the container only inspects Java classes annotated with a bean defining annotation during bean discovery. Bean defining annotation is any scope type (e.g. @RequestScoped, @Dependent). So this is more like good old Seam2 where a component must be explicitly designated. I think this is the real benefit of implicit bean archives in CDI 1.1 - disable automatic inspection of all types present in the archive without the need of exclude filters defined in beans.xml (exlude filters are now part of the spec, previously a special feature of Weld).


And now the issue. CDI is built on top of JSR 330 and makes use of its annotations (@Inject, @Qualifier, ...). Unfortunately javax.inject.Scope identifies pseudo-scopes in CDI. And so any archive (even not intended to be a CDI bean archive) which contains a class annotated with any scope annotation becomes an implicit bean archive, i.e. beans are discovered, validated, etc. This might cause problems with archives which use any other injection framework based on JSR 330 (e.g. very useful Guava - Issue 1433).


One solution is to use beans.xml with the bean-discovery-mode of "none" - this tells the container to skip the archive. However this also breaks backwards compatibility, because such an archive will be recognized in CDI 1.0.


The CDI 1.1 also states:

"For compatibility with Contexts and Dependency 1.0, products must contain an option to cause an archive to be ignored by the container when no beans.xml is present."

It seems this is the only way to handle this issue correctly. On the other hand it makes your application non-portable. If you have any idea how to fix it post a comment to CDI-377.


UPDATE: A colleague of mine (thanks Jozef!) pointed out that there is one more possibility - according to the spec an archive which contains a CDI extension and no beans.xml file is not a bean archive either. But of course this is rather a hack solution for our problem.


See also the CDI 1.1 specification, section 12.1. Bean archives and 12.4. Bean discovery.

This is a new feature introduced in Weld 2.1.0.Beta2 (see also WELD-1480 and WELD-1501). It's not portable (i.e. will not work with other CDI implementations) but might be useful.


According to the CDI specification some built-in contexts (request, session and conversation) must be always active during the service() method of any servlet in the web application. This means context activation and deactivation per every HTTP request and also handling conversation stuff (e.g. associating long running conversation with the request) in the case of conversation context. For some scenarios this represents unnecessary overhead. The first scenario example that comes to my mind is serving resources (CSS, JavaScript, images, audio, etc.). But it may also apply to legacy components which do not make use of CDI services.


Weld allows to define a special activation filter component - HttpContextActivationFilter - so that only matching HTTP requests result in context activation/deactivation. Basically there are two ways to enable/configure this component. First the integrator (e.g. WildFly application server) is allowed to provide an implementation and utilize its own configuration mechanism. Secondly - if the integrator doesn't support this option - a special initialization parameter may be associated with a web application to activate a built-in regular expression-based activation filter.


E.g. to match paths with suffix ".html" and ".xhtml" place the following init param in your web.xml:



Param value is a regular expression and is matched againts the request URI without the context path, i.e. /foo for http://localhost:8080/myapp/foo?action=test (try Visual Regex Tester from to test your mappings if not sure :-). Note that Weld only supports one activation filter at a time and integrator has always precedence. You should see a warning log if your web.xml mapping definition is ignored.


My quick and dirty tests showed up that using built-in regular expression-based activation filter can save several milliseconds* for each request which does not require CDI services. It's not that much but it counts!


* Resource consumption was not monitored.

I assume everyone who has ever used Seam 2, JSF 1.x and RichFaces 3 knows the concept of Seam conversations and RF3 ajax components (a4j:support, a4j:commandLink, a4j:commandButton, etc.). The use of RF3 controls and Seam conversations is quite straightforward. Put the RF3 control on the facelet page, handle some ajax actions in Seam component, at some time promote temporary conversation to long-running, and finally rerender required parts of JSF page. Everything works. No need to put conversation id somewhere provided you don't leave the JSF view (or do non-JSF request).


Today's applications mostly switched to CDI (Weld), JSF 2 and RichFaces 4. As expected some problems may occur during migration of programming techniques. One of them might disrupt the previous experience...


Check following facelets fragment - Seam2/JSF/RF3:

<h:form id="form">

    value="Begin conversation" 
    action="#{action.beginConversation}" />

    value="Do action"
    action="#{action.doSomethingInContextOfLongRunningConversation}" />



Clicking button A - begins conversation (Action#beginConversation promotes temporary conversation to long-running). Then clicking button B - the conversation is automatically propagated. Note that we do no rerendering. However for the same facelets fragment running on Weld/JSF2/RF4 the conversation is not automatically propagated. This also applies to native JSF components (f:ajax). Where is the problem? CDI does not define built-in JSF page/view scope so that it cannot restore conversation id from this context (like Seam 2 does). It only relies on HTTP request parameter cid. To have it working you will have to...


1) Rerender the whole form (Weld will automatically append the conversation id to form's action attribute):

<h:form id="form">

    value="Begin conversation"
    render="@form" />

    value="Do action"
    action="#{action.doSomethingInContextOfLongRunningConversation}" />





2) Propagate conversation id manually:

<h:form id="form">
      value="Begin conversation"
      render="B" />
     value="Do action"
       <f:param name="cid" value="#{}"/>



See also org.jboss.weld.jsf.ConversationAwareViewHandler.

The development of CDI TCK 1.1 (focused on CDI 1.1/JSR 346) is moving forward and the TCK test suite expands in many areas. Last week the total coverage reached 90%! And now some numbers to compare...

CDI TCK 1.0: Total coverage is 76,02% (1005 of 1322 testable assertions tested). The worst chapter coverage is 72,87%. The best chapter coverage is  89,36%.

CDI TCK 1.1: Up to date total coverage is 90,08% (1280 of 1421 testable assertions tested). That's 14% increase even though there are currently 99 more testable assertions. The worst chapter coverage is 83,64%. The best chapter coverage is 100%.


In any case I believe that this results could not be achieved without the great support of Weld development team and also without such a great projects like ShrinkWrap, Arquillian and JBoss Application Server 7.


Thanks to anyone involved!

Last summer CDI TCK project moved to GitHub [1] and recently the very first version of Technology Compatibility Kit for JSR-346 (CDI TCK 1.1.0.Aplha1) was released [2]. We decided to make some cleanup work to avoid confusion and misunderstanding. Since CDI TCK 1.1 relates to JSR-346 and not JSR-299 the source package and maven groupId org.jboss.jsr299.tck was renamed to org.jboss.cdi.tck. Unfortunately not everything went well. At first sight the history seemed to be lost... Well, the good news is that the history is not lost. The bad news is that nor the GitHub web UI nor the Eclipse EGit handle this correctly. As far as I know right now the only way to get the history of TCK source files is to use command line, git log and --follow switch ("Continue listing the history of a file beyond renames"). Although EGit has "Follow Renames" option in history view this is not working for me at all [3]. As of GitHub - I did not find any relevant information. Hopefully things will change quickly.