News

First release candidate of Weld 2.4

2016-8-19   release   Martin Kouba

I am pleased to announce the first release candidate of Weld 2.4 (CDI 1.2). See also the release details. Thanks to everyone involved in this release!

Removed dependency on com.google.guava:guava

Weld does not depend on com.google.guava:guava anymore (actually, Weld 3 does not depend on guava since 3.0.0.Alpha2). This significantly reduces the footprint of both Weld SE and Weld Servlet. The dependency is also not bundled with shaded artifacts for Weld SE and Weld Servlet.

Enhanced version of javax.enterprise.inject.Instance

Weld now provides org.jboss.weld.inject.WeldInstance - an enhanced version of javax.enterprise.inject.Instance. There are three additional methods - getHandler(), handlers() and isResolvable(). A handler allows to inspect the metadata of the relevant bean and to destroy the underlying contextual instance. isResolvable() is just a convenient method - a replacement for !isUnsatisfied() && !isAmbiguous(). For more details see also the reference guide.

WeldInstance is automatically available in Weld SE and Weld Servlet where the Weld API is always on the class path. It is also available in Weld-powered EE containers. In this case, users would have to compile their application against the Weld API and exclude the Weld API artifact from the deployment (e.g. use provided scope in Maven).

This functionality is based on a new proposal for CDI-589.

Veto AnnotatedType not annotated with bean defining annotation

Sometimes it might be useful to process all types during bootstrap, i.e. fire/observe ProcessAnnotatedType event for each Java class discovered, but veto types which are not annotated with a bean defining annotation. The main reason is that not all classes that meet all of the necessary conditions are intended to become beans. And so vetoing such types helps to conserve memory used by the container. Note that if you use bean-discovey-mode=annotated (implicit bean archive) then no ProcessAnnotatedType will be fired for any such type because it’s not discovered at all. And there might be portable extensions which use ProcessAnnotatedType to extract some important information from classes which are not beans.

Therefore, Weld allows to use bean-discovey-mode=all (explicit bean archive) and veto types without a bean defining annotation whose AnnotatedType#getJavaClass().getName() matches a regular expression. In other words, a type is vetoed if its name matches a regular expression and at the same time is not annotated with a bean defining annotation. This functionality is implemented as a built-in portable extension processing all types from all bean archives (it was already doable using an extension but we believe it’s more convenient to have this functionality out of the box).

This is a workaround for problems of bean-discovey-mode=annotated mentioned in CDI-420.

@ActivateRequestScope moved to Weld API

This interceptor binding can be used to activate the request scope within a business method invocation. It was previously part of the Weld SE but we believe it might be useful in any environment. See also WELD-2150.

Improved rolling upgrades support

Lenny Primak (a Weld community member - thanks for the report again!) struggled with rolling upgrades on certain application servers (Payara, GlassFish). Therefore, a new configuration property was introduced. This property allows to specify a delimiter which is used to abbreviate a bean archive identifier (which is usually derived from the archive name) before used as a part of an identifier of an internal component (such as bean). See also the reference guide and WELD-2064.

Events - reflect the output of CDI-494

This change reflects the clarification around Event operations - "A wildcard type is not considered an unresolvable type variable". See also WELD-2137 and CDI-494. Simply said, the snippet below and similar ones should now work:

@Inject Event<List<?>> event;
    
    public void fireLists() {
      List<String> stringList = new ArrayList<>();
      event.fire(stringList);
      List<Integer> intList = new ArrayList<>();
      event.fire(intList);
    }
    
    void observeAllLists(@Observes List<?> anyList) {
      // Will be notified
    }

Probe - allow to filter unused beans

The Probe development tool now identifies beans which are most likely unused (a bean is considered unused if it has no direct dependents, does not declare any observer or producer methods, is not annotated with @Named and is not a built-in bean, extension, interceptor or decorator). This might be useful to identify types suitable for vetoing as mentioned in [_veto_code_annotatedtype_code_not_annotated_with_bean_defining_annotation].

Cleanup

Weld has underwent an internal cleanup. A lot of deprecated and unused classes were removed.

Initial Java 9 support

It’s now possible to build Weld with Java 9. Note that this does not mean that Weld is modularized in a Jigsaw way. It’s just the first step on a long road ;-).

Bugs

Last but not least - a few bugs were killed. Weld SE - provided ClassLoader is also used to load extensions (WELD-2209). AnnotatedTypeValidator does consider extended interfaces (WELD-2221). Invocation of a JDK8 default method should be intercepted (this only works if using jboss-classfilewriter 1.2.0.Beta1+, WELD-2093).

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.


Arquillian container Weld 2.0.0.Beta1 released!

2016-7-21   arquillian , testing   Tomas Remes

We are pleased to announce a release of embedded Arquillian container adapter for Weld. This container has deserved some love for really long time. We tried to refactor it and introduced new master branch which now corresponds to the 2.0.0.x version stream. The original master was branched in 1.0. There is no more any arquillian-weld-ee-embedded-1.1 or arquillian-weld-se-embedded. It’s squashed to one arquillian-weld-embedded and you can configure environments either programmatically or using configuration properties. See link:https://github.com/arquillian/arquillian-container-weld This new version is going to be used in Weld as soon as possible.

Maven Coordinates:
    <dependency>
            <groupId>org.jboss.arquillian.container</groupId>
            <artifactId>arquillian-weld-embedded</artifactId>
            <version>2.0.0.Beta1</version>
        </dependency>

We would really appreciate if you can try it and let us know your experience!


Weld 2.3.5.Final

2016-7-1   release , plans   Martin Kouba

The next version of the stable 2.3 branch has been released! See also the release details. Thanks to everyone involved in this release!

We plan to create the 2.4 branch of Weld within a few weeks. Weld 2.4 will remain a CDI 1.2 implementation. We would like to do some cleanup (e.g. remove deprecated classes from Weld SE), enhance the API and also add some new features. See also the list of issues for 2.4.0.CR1.

Notable bugfixes and improvements:

  • fixed static disposer method invocation (WELD-2176)

  • fixed private observer/producer/disposer invocation on a bean with decorator (WELD-2179)

  • fixed Instance.destroy() for dependent session beans (WELD-2148)

  • fixed ArraySet.hashCode() to comply with java.util.Set.hashCode() contract (WELD-2185)

  • log veto actions and modifications of lists returned by AfterTypeDiscovery (WELD-2170, WELD-2171)

  • log a warning when a class is annotated with a scope but does not declare an appropriate constructor (WELD-2178)

  • support extension deployed in multiple WARs in an EAR (WELD-2143)

  • detect non-unique BeanDeploymentArchive identifier (WELD-2165)

  • Weld Servlet

    • fixed extraction of bean archive id - problem occures with embedded Jetty (WELD-2161)

    • improve the way JandexDiscoveryStrategy identifies an annotation annotated with @NormalScope (WELD-2160)

    • weld-servlet-core declares dependency on weld-core-jsf

  • Weld SE

    • do not pass system properties to Weld configuration (WELD-2146)

  • Probe - allow to test bean availability in a given bean archive

    • check for example the availability of an alternative in the demo application

  • many documentation and reference guide updates

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.


Update on weld-vertx

2016-6-21   vertx , integration   Martin Kouba

This is a follow-up on the article Weld meets Vert.x. Weld team has just released the first alpha version of weld-vertx (artifacts are available in Maven Central). Since the last time we talked about weld-vertx two new features were added. First, it’s possible to inject the relevant io.vertx.core.Vertx and io.vertx.core.Context instances direcly into beans. Also there is a new module called weld-vertx-web which extends functionality of weld-vertx-core and io.vertx:vertx-web and allows to register Route handlers discovered during container initialization. In other words, it’s possible to configure a Route in a declarative way:

import javax.inject.Inject;
    
    import org.jboss.weld.vertx.web.WebRoute;
    
    import io.vertx.core.Handler;
    import io.vertx.ext.web.RoutingContext;
    
    // This annotation is used to configure a Route
    @WebRoute("/hello")
    public class HelloHandler implements Handler<RoutingContext> {
    
        @Inject
        SayHelloService service;
    
        @Override
        public void handle(RoutingContext ctx) {
            ctx.response().setStatusCode(200).end(service.hello());
        }
    
    }

The registered handler instances are NOT real bean instances, i.e. they’re not managed by the CDI container (similarly as Java EE components). However, the dependency injection is supported.

The central point of integration is the org.jboss.weld.vertx.web.WeldWebVerticle. This Verticle extends org.jboss.weld.vertx.WeldVerticle and provides the WeldWebVerticle.registerRoutes(Router) method:

 class MyApp {
    
         public static void main(String[] args) {
             final Vertx vertx = Vertx.vertx();
             final WeldWebVerticle weldVerticle = new WeldWebVerticle();
    
             vertx.deployVerticle(weldVerticle, result -> {
    
                 if (result.succeeded()) {
                     // Configure the router after Weld bootstrap finished
                     Router router = Router.router(vertx);
                     router.route().handler(BodyHandler.create());
                     weldVerticle.registerRoutes(router);
                     vertx.createHttpServer().requestHandler(router::accept).listen(8080);
                 }
             });
         }
     }

Give it a try and let us know if you have any idea how to extend the functionality of weld-vertx. Any feedback is appreciated!


Programmatic lookup improvements

2016-5-18   api , draft   Martin Kouba

javax.enterprise.inject.Instance is sometimes invaluable companion. For example, Instance allows you to handle unsatisfied and ambiguous dependencies gracefully. E.g. it’s possible to avoid unnecessary deployment problems:

interface OrderProcessor {
      void process(Order order);
      int getPriority();
    }
    
    class OrderService {
    
      @Inject
      Instance<OrderProcessor> instance;
    
      void create(Order order) {
        if (!instance.isUnsatisfied() && !instance.isAmbiguous()) {
            instance.get().process(order);
        } else {
            // Log a warning or throw an exception
        }
      }
    }

It is less known that Instance extends Iterable and so it allows to iterate through contextual references of beans with the specified combination of required type and qualifiers. This might be useful if the set of beans satisfying the given type and qualifiers is not known beforehand. We may also need to resolve ambiguities manually, e.g. inspect all the instances and choose only those matching our needs.

@ApplicationScoped
    class OrderService {
    
      @Inject
      @Any
      Instance<OrderProcessor> instance;
    
      void create(Order order) {
        for (OrderProcessor processor : instance) {
            if (processor.getPriority() > 10) {
                processor.process(order);
            }
        }
      }
    }

Another interesting use case might be selecting exactly one implementation:

@ApplicationScoped
    class OrderService {
    
      @Inject
      @Any
      Instance<OrderProcessor> instance;
    
      void create(Order order) {
        List<OrderProcessor> processors = new ArrayList<>();
        for (OrderProcessor processor : instance) {
            processors.add(processor);
        }
        Collections.sort(processors, Comparator.<OrderProcessor> comparingInt(p -> p.getPriority()).reversed());
        // Use the processor with highest priority
        processors.get(0).ping();
      }
    }

This works nice. But we have to pay extra attention to the scopes. If a Processor implementation is @Dependent a similar usage results in memory leaks. What’s the reason? The Processor instance is the dependent object of Instance<OrderProcessor> which is the dependent object of OrderService. And so each Instance.get() will produce a new Processor bound to the lifecycle of the OrderService. To avoid the leak we should always call Instance.destroy() method in similar cases. However, Instance.destroy() always destroys the underlying contextual instance! Even if you pass e.g. a client proxy of an @ApplicationScoped bean. This is not always desirable. Currently, it’s quite complicated to detect a dependent bean inside the loop.

To extend the possibilities the Weld team is experimenting with org.jboss.weld.inject.WeldInstance - an enhanced version of javax.enterprise.inject.Instance. There are three new methods we find useful. The first one - getHandler() - allows to obtain a contextual reference handler which not only holds the contextual reference but also allows to inspect the metadata of the relevant bean and to destroy the underlying contextual instance. Moreover, the handler implements AutoCloseable:

import org.jboss.weld.inject.WeldInstance;
    
    class Foo {
    
      @Inject
      WeldInstance<Bar> instance;
    
      void doWork() {
        try (Handler<Bar> bar = instance.getHandler()) {
            bar.get().doBusiness();
            // Note that Bar will be automatically destroyed at the end of the try-with-resources statement
        }
    
        Handler<Bar> bar = instance.getHandler()
        bar.get().doBusiness();
        // Calls Instance.destroy()
        bar.destroy();
      }
    
    }

The next method - handlerIterator() - returns an iterator over contextual reference handlers. This might be useful if you need more control over contextual references inside the loop:

@ApplicationScoped
    class OrderService {
    
      @Inject
      @Any
      WeldInstance<OrderProcessor> instance;
    
      void create(Order order) {
        for (Iterator<Handler<OrderProcessor>> iterator = instance.handlerIterator(); iterator.hasNext();) {
                Handler<OrderProcessor> processor = iterator.next();
                processor.get().process(order);
                if (processor.getBean().getScope().equals(Dependent.class)) {
                    // Destroy only dependent processors
                    processor.destroy();
                }
            }
      }
    }

The last one is just a convenient method - isResolvable() - a replacement for !isUnsatisfied() && !isAmbiguous() which is the expression most users are interested in:

class OrderService {
    
      @Inject
      Instance<OrderProcessor> instance;
    
      void create(Order order) {
        if (instance.isResolvable()) {
            instance.get().process(order);
        } else {
            // Log a warning or throw an exception
        }
      }
    }

Weld team is considering adding org.jboss.weld.inject.WeldInstance to the Weld API (2.4 and 3.0). WeldInstance would be automatically available in Weld SE and Weld Servlet where the Weld API is always on the class path. It would be also available in Weld-powered EE containers - in this case, users would have to compile their application against the Weld API and exclude the Weld API artifact from the deployment (e.g. use provided scope in Maven).

See also WELD-2151 and the work in progress: https://github.com/mkouba/core/tree/WELD-2151. And feel free to add comments to this blog post. Any feedback is appreciated!